Frank Boccia
Frank Boccia

Reputation: 248

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)) }

Upvotes: 1

Views: 804

Answers (3)

Ron Myschuk
Ron Myschuk

Reputation: 6071

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
    }
}

Upvotes: 2

Nisarg Shah
Nisarg Shah

Reputation: 754

You can try something like this

UIView.animate(withDuration: 5, animations: {
        self.spaceShip.transform = CGAffineTransform(scaleX: 60, y: 40)
},
completion: { _ in
    UIView.animate(withDuration: 2) {
        self.spaceShip.transform = .identity // Reset your view
    }
})

Upvotes: 0

Mickael Belhassen
Mickael Belhassen

Reputation: 3352

You can animate the view like this:

UIView.animate(withDuration: 5, animations: {
        self.spaceShip.scale(to: CGSize(width: 60, height: 40))
},
completion: { _ in
    UIView.animate(withDuration: 2) {
        self.spaceShip.transform = .identity // Reset your view
    }
})

Upvotes: 0

Related Questions