简体   繁体   English

Swift SpriteKit为GameScene添加计时器

[英]Swift SpriteKit Add timer to GameScene

I have looked around at many articles, but none of them seem to make sense or are relevant to my issue. 我浏览了许多文章,但似乎没有任何意义或与我的问题相关。 I want to give the user a set time to press a node. 我想给用户设定时间来按下一个节点。 If they succeed in pressing the node within the set time the timer should reset, if they fail to press the node within the set time it will be game over. 如果他们在设定时间内成功按下节点,计时器应重置;如果他们未能在设定时间内按下节点,游戏将结束。

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first!
        if square.contains(touch.location(in: self)) {
            moveSquare()
            GameScene.score+=1
            scoreLabel.text = "\(GameScene.score)"
            }
        } else {
            gameOverScene()
        }
}

so my question is how do I set the timer up to achieve those requirements, and where do I put the code? 所以我的问题是如何设置计时器以满足这些要求,并将代码放在哪里?

Use SKActions instead of timers: 使用SKActions代替计时器:

let countdown = SKAction.sequence([SKAction.wait(forDuration: 5),
                                   SKAction.perform(#selector(gameOver), onTarget: Self)])
run(countdown, withKey: "gameOverTimer")

(this assumes that the function gameOver is the one you want to call if the correct button is not touched in time) (这假设如果未及时触摸正确的按钮,则gameOver函数是您要调用的函数)

and in touchesBegan , if the correct node is touched: 并在touchesBegan ,如果触摸了正确的节点:

removeAction(forKey: "gameOverTimer")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM