user3773099
user3773099

Reputation: 73

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

Upvotes: 5

Views: 5137

Answers (2)

Rafael
Rafael

Reputation: 7242

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.

Upvotes: 2

meisenman
meisenman

Reputation: 1828

https://stackoverflow.com/a/24195006/2494064

Here is a link to an answer that removes nodes that go off the top of the screen. You would just have to replicate this to cover the entire border and set all of the walls to have the same contactBitMask values.

Basically the logic is to remove the SKSpriteNodes when they contact physicsbodies that you have resting just outside the visible screen.

Upvotes: 1

Related Questions