Mohamed Ismail
Mohamed Ismail

Reputation: 25

How to create a delay before changing a variable in SpriteKit

I am creating a game that involves the player to use powerups. Whenever the player chooses to activate the powerup, this function is run. It changes the image of the player to the one of the player using a powerup, and changes the collision physics so that the player is now immune to enemies.

It does this whenever the variable powerActivated is 1, however as you can see it goes straight back to 0. I need it to delay for 5-10 seconds and then go to 0. This will allow the user to use the powerUp for a few seconds before it goes away.

 func superAbility(){

        powerActivated = 1

        if powerActivated == 1 {

        player.texture = SKTexture(imageNamed: "heroWithPower")
        player.physicsBody!.categoryBitMask = PhysicsCategories.PowerUp
        player.physicsBody!.collisionBitMask = PhysicsCategories.None
        player.physicsBody!.contactTestBitMask = PhysicsCategories.Enemy

        // delay should be here

        powerActivated = 0

        }

        else {
            player.texture = SKTexture(imageNamed: "hero")
            player.physicsBody!.categoryBitMask = PhysicsCategories.Player
            player.physicsBody!.collisionBitMask = PhysicsCategories.None
            player.physicsBody!.contactTestBitMask = PhysicsCategories.Enemy

        }

Upvotes: 0

Views: 97

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

Use SKAction's to create the delay, this way you are waiting in game time and not real time, so any external phone actions like a phone call will not screw with your game.

func superAbility(){

        player.texture = SKTexture(imageNamed: "heroWithPower")
        player.physicsBody!.categoryBitMask = PhysicsCategories.PowerUp
        player.physicsBody!.collisionBitMask = PhysicsCategories.None
        player.physicsBody!.contactTestBitMask = PhysicsCategories.None //I think you meant to set this to none to be immune to enemies

        let deactivateAction = SKAction.run{
            [unowned self] in
            self.player.texture = SKTexture(imageNamed: "hero")
            self.player.physicsBody!.categoryBitMask = PhysicsCategories.Player
            self.player.physicsBody!.collisionBitMask = PhysicsCategories.None
            self.player.physicsBody!.contactTestBitMask = PhysicsCategories.Enemy
        }
        let wait = SKAction.wait(forDuration:5)
        let seq = SKAction.sequence([wait,deactivateAction])
        player.run(seq, withKey:"powerup")
}

Upvotes: 2

Related Questions