Search code examples
iosswiftsprite-kitskspritenode

Check if nodes are off the screen


I have a node on my screen that is moved with the gyroscope. But I can't limit it's position to the screen, I have tried this, but it only worked for the bottom and the the top:

override func update(currentTime: CFTimeInterval){

     ...

     if sprite.position.x <= sprite.frame.width / 2 {
          print("out on the left of the screen")
     }
     if sprite.position.x >= self.frame.width - sprite.frame.width / 2 {
          print("out on the right of the screen")
     }
     if sprite.position.y <= sprite.frame.height / 2 {
          print("out on the top of the screen")
          //worked
     }
     if sprite.position.y <= self.frame.height - sprite.frame.height / 2 {
          print("out on the bottom of the screen")
          //worked
     }

}

Solution

  • Since you're trying to stop the sprite going off screen I'd recommend you use Sprite Kit's physics engine.

    Firstly, add an SKPhysicsBody to your sprite, for example:

    sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
    

    Secondly, you need to add a physics body to the scene, for example:

    override func didMoveToView(view: SKView) {
        super.didMoveToView(view)
        self.physicsBody = SKPhysicsBody(edgeLoopFromRect: view.bounds)
    }
    

    Finally, since you want gravity disabled you can either disable it just for sprite:

    sprite.physicsBody!.affectedByGravity = false
    // force unwrapping here is okay because we're SURE sprite has a physics body.
    

    or, disable gravity for everything in the scene:

    self.physicsWorld.gravity = CGVector.zeroVector
    // self in this case is your `SKScene` subclass.
    

    For more information The Sprite Kit Programming Guide is really useful, in the case of physics see the Simulating Physics section.