0
votes

It is my understanding that SKSpriteNodes that have been added to the SKScene will linger there until removeFromParent(), or any of the other remove methods are called.

I haven't touched SpriteKit for 2 months, and that's what I remember it to be. But for some reason, today when I was programming, I realized something odd; I was looking at my node count and it was not being increased even though I am doing a .repeatActionForever that keeps instantiating a new SKSpriteNode that runs across the screen. There are no remove calls anywhere in the code. Here's the block of code that creates the SKSpriteNode:

//function in GameScene
func spawnEnemy() {
    let enemy = SKSpriteNode(imageNamed: "enemy")
    enemy.position = CGPoint(x: size.width + enemy.size.width/2, y: size.height/2)
    let actionMove = SKAction.moveToX(-enemy.size.width/2, duration: 2.0)
    enemy.runAction(actionMove)
}

//inside update()
runAction(SKAction.repeatActionForever(SKAction.runBlock(spawnEnemy))

Here's a gif of what the simulator showed: http://i.imgur.com/c8eyFDE.gif

I was under the impression that the stampede of old lady in dresses would linger off the screen and the node count for continue to build up, but for some reason, the node count stays constant at 42 nodes, as if the nodes that are off screen are automatically removed.

Again, I have no remove calls anywhere.

2

2 Answers

2
votes

The node count only counts the nodes visible on screen. Therefore you've got a constant 42 nodes on screen and many more off screen.

To check nothing is being removed though, you could subclass SKSpriteNode like so:

class Enemy : SKSpriteNode {
    override func removeFromParent() {
        super.removeFromParent()
        println("An enemy was removed!")
    }
}

Then in your scene:

let enemy = Enemy(imageNamed: "enemy")

Now, if an enemy is somehow being removed you'll definitely know.

If it turns out the enemies are persisting after they've moved off the screen I would recommend using either of the following to remove the nodes:

1. Use runAction(_ action: SKAction!, completion block: (() -> Void)!) like so:

enemy.runAction(actionMove) { enemy.removeFromParent() }

2. Use SKAction.removeFromParent() and create a sequence of SKActions:

let actionMove = SKAction.moveToX(-enemy.size.width/2, duration: 2.0)
let remove = SKAction.removeFromParent()

enemy.runAction(SKAction.sequence([actionMove, remove]))

Hope that helps answer you question.

1
votes

There may be some bugs in your code:

1.I hadn't see any code about adding a node in the scene. Enemies need to be added to the scene or child of the scene.
2.The method repeadActionForever doesn't need to be called for more than one times. It will run the block inside automatically.

Try to fix them and let me know what happens.