Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sprite Kit Remove SKNode From Parent When Off Screen

I would like to know how to remove my SKNodes when they are off screen to help my game run more smoothly.

How To Do This On Sprite Kit

Thanks So Much

like image 432
user3773099 Avatar asked Nov 01 '22 21:11

user3773099


1 Answers

Here is an easy solution in Swift 4:

class GameScene: SKScene {
    let s = SKLabelNode(fontNamed: "Chalkduster")

    override func didMove(to view: SKView) {
      s.text = "test"
      s.fontSize = 50
      addChild(s)

      let moveRight = SKAction.moveBy(x: 40, y: 0, duration: 0.5)
      s.run(SKAction.repeatForever(moveRight))
    }

    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered
        if ((s.parent != nil) && !intersects(s)) {
            s.removeFromParent()
            print("Sprite removed.")
        }
    }
}

You have a sprite (in this case a SKLabelNode but any sprite node will do) that is moving horizontally and you want to delete this sprite once is out of the frame bounds.

You can use the intersects function to check this and then remove that sprite from its parent. I have also checked that the sprite has a parent before removing it (by checking if s.parent is not nil) as we wish to remove the sprite only once.

like image 54
Rafael Avatar answered Nov 18 '22 18:11

Rafael