简体   繁体   中英

How to remove node when become outside the scene in Sprite Kit

I am trying to delete node when goes out side the scene and i tried this method to do it

if( CGRectIntersectsRect(node.frame, view.frame) ) {
   // Don't delete your node
} else {
   // Delete your node as it is not in your view
}

but it seems not working any help would be appreciated

This is not going to be the best approach by a performance point of view but if you override the update method in your scene you will be able to write code that gets executed each frame so.

class GameScene : SKScene {

    var arrow : SKSpriteNode?

    override func update(currentTime: NSTimeInterval) {
        super.update(currentTime)

        if let
            arrow = arrow,
            view = self.view
        where
            CGRectContainsRect(view.frame, arrow.frame) == false &&
            CGRectIntersectsRect(arrow.frame, view.frame) == false {
                arrow.removeFromParent()
        }
    }
}

Considerations

Please keep in mind that every code you write inside the update method is executed each frame (60 times per second on a 60fps game) so you should be very careful about that. Typical things you don't want to write inside the update unless it is strictly necessary:

  1. creation of objects
  2. big loops
  3. recursive calls
  4. any crazy code that requires too much time to be executed

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM