简体   繁体   中英

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:

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)

and in touchesBegan , if the correct node is touched:

removeAction(forKey: "gameOverTimer")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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