Search code examples
swiftsprite-kitsklabelnode

Animate a number changing in SpriteKit


I'm using Swift and SpriteKit. I want a number to change from 20 to 10. I want while its changing to display the changing of the number. To be more specific, I want 19 to show for 0.1 seconds, 18 to show for 0.1 seconds, and so on.


Solution

  • I found an answer:

    var counterNumber = 20
    var counterLabel = SKLabelNode()
    
    override func didMoveToView(view: SKView) {
        /* Setup your scene here */
    
        counterLabel.text = "\(counterNumber)"
        counterLabel.fontName = "Helvetica Neue"
        counterLabel.fontSize = 100
        counterLabel.fontColor = SKColor.blackColor()
        counterLabel.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
        self.addChild(counterLabel)
    
    
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
       /* Called when a touch begins */
    
        let wait = SKAction.waitForDuration(0.5)
        let block = SKAction.runBlock({
    
            self.counterNumber = self.counterNumber - 1
            self.counterLabel.text = "\(self.counterNumber)"
    
        })
    
        let sequence = SKAction.sequence([wait, block])
    
        counterLabel.runAction(SKAction.repeatAction(sequence, count: 10))
    
    
    }