chris
chris

Reputation: 4996

Adding SKNodes to SKScene slowing animation

I have a SKScene, in which I have a timer callback (not run loop) that at each time step updates the scene by adding and/or removing SKNodes. The idea is to animate the nodes travelling down in a straight line. Below is the code in my callback.

    // 1. Add new nodes

    let newSprite = SKSpriteNode(imageNamed: "file")

    newSprite.position = (pos, pos)
    spriteList.append((sprite: newSprite, position: 0))
    scene.addChild(newSprite)

    var removeList = [Int]()

    let action = SKAction.move(to: (new, pos), duration: 5.0)
    newSprite.run(action)

    // 2. Update node positions
    for (i,_) in spriteList.enumerated() {
        spriteList[i].position += 1
        if spriteList[i].position > gridLength {
            removeList.append(i)
        }
    }

    // 3. Remove old nodes
    for i in removeList {
        spriteList[i].sprite.removeFromParent()
        spriteList.remove(at: i)
    }

At the moment, each time this callback runs, the animation stutters. When the callback stops and I have no more nodes to add, the rest of the nodes in the scene animate smoothly down. Any suggestions how I can fix this? Is the problem adding the nodes, running the logic, or something else entirely?

Upvotes: 0

Views: 176

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59496

I have a SKScene, in which I have a timer callback (not run loop)

Don't do it

You should never use timers with SpriteKit, always stick to the run loop instead.

Actions

If you want to repeat a block of code every n seconds just use actions

class Scene: SKScene {
    override func didMove(to view: SKView) {
        super.didMove(to: view)

        let action = SKAction.run { [unowned self] in
            // <--- put the codwe you want to repeat every 2 seconds here
        }

        let wait = SKAction.wait(forDuration: 2)
        let sequence = SKAction.sequence([action, wait])
        let repeatForever = SKAction.repeatForever(sequence)
        run(repeatForever)
    }
}

Upvotes: 2

Related Questions