Ryan Broman
Ryan Broman

Reputation: 35

SKSpriteNode doesn't delete when falls off scene

My app (Swift 2) doesn't delete any nodes when they fall off of the scene. Eventually they'll take up space and down the framerate. My code can be found at https://github.com/Ph0enix0/Loominarty-Confirmed/blob/master/Loominarty%20Confirmed/GameScene.swift Thank you!

Upvotes: 1

Views: 434

Answers (1)

Whirlwind
Whirlwind

Reputation: 13675

For your situation, based on how you move bullet, the easiest solution would be to use action sequence. Like this :

func SpawnBullets(){
    var bullet = SKSpriteNode(color: SKColor.orangeColor(), size: CGSize(width: 10, height: 20))
    bullet.zPosition = -5
    bullet.position = CGPointMake(player.position.x, player.position.y)



    let action = SKAction.moveToY(self.size.height + 30.0, duration: 0.6)

    let remove = SKAction.runBlock({bullet.removeFromParent(); println("Bullet removed from scene")})

    let sequence = SKAction.sequence([action,remove])

    bullet.runAction(sequence)

    bullet.physicsBody = SKPhysicsBody(rectangleOfSize: bullet.size)
    bullet.physicsBody?.categoryBitMask = physCat.bullet
    bullet.physicsBody?.contactTestBitMask = physCat.enemy
    bullet.physicsBody?.affectedByGravity = false
    bullet.physicsBody?.dynamic = false

    self.addChild(bullet)
}

You are probably aware of this, but not hurt to mention that removing off-screen nodes is a good habit because every node added to the node tree stays there and consumes resources until it is removed.

Upvotes: 1

Related Questions