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

时间:2019-04-14 19:22:59

标签: swift sprite-kit delay

我正在创建一个涉及玩家使用道具的游戏。每当播放器选择激活加电功能时,便会运行此功能。它会使用加电功能将玩家的图像更改为其中一名玩家的图像,并更改碰撞物理效果,从而使玩家现在对敌人免疫。

只要变量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

        }

1 个答案:

答案 0 :(得分:2)

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

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