如何在更改 SpriteKit 中的变量之前创建延迟

How to create a delay before changing a variable in SpriteKit

我正在创建一个让玩家使用道具的游戏。每当玩家选择激活 powerup,这个函数就是 运行。它将玩家的图像更改为使用通电的玩家之一,并更改碰撞物理,使玩家现在对敌人免疫。

它会在变量 powerActivated 为 1 时执行此操作,但是如您所见,它会直接返回 0。我需要它延迟 5-10 秒然后返回 0。这将允许用户使用powerUp 几秒钟后消失。

 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

        }

使用 SKAction 来创建延迟,这样您就可以在游戏时间而不是实时等待,因此任何外部 phone 操作(例如 phone 调用都不会影响您的游戏。

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