Search code examples
swiftalgorithmsprite-kitskspritenode

How to execute a function for 5 seconds in swift


I am creating a game, this function is used as a power up to shrink the sprite. I want this function to execute for 5 seconds, and attach this 5 second timer to a label as a count down. After the function ends, return the sprite to its original size.

The function just shrinks the node by setting the scale.

func shrinkShip() { spaceShip.scale(to: CGSize(width: 60, height: 40)) }


Solution

  • Sticking with SpriteKit I would just do the following

    func shrinkShip(duration: Double) { 
    
        let originalSize = spaceShip.size
    
        spaceShip.scale(to: CGSize(width: 60, height: 40)) 
    
        for x in 0..<Int(duration) {
    
            //increment the timer every 1 second for the duration
            self.run(SKAction.wait(forDuration: 1 * Double(x))) {
                self.timerLabel.text = String(Int(duration) - x)
            }
        }
        self.run(SKAction.wait(forDuration: duration)) {
            //return the spaceship to full size
            self.spaceShip.scale(to: originalSize) 
            //hide the timer
            self.timerLabel.text = ""
            self.timerLabel.isHidden = true
        }
    }