如何使用 Swift 在 Sprite 套件游戏中创建 NSTimer?

How can you create an NSTimer in a Sprite kit game with Swift?

单视图控制器应用程序中,您可以使用:

Foundation.Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(GameViewController.updateFunction), userInfo: nil, repeats: true)

但是,当您在 Spritekit 游戏中使用该代码时,它会出现错误并且无法运行。

我可以用什么 有效

像这样启动你的计时器:

class GameScene: SKScene{

    var timer: Timer!

    override func didMove(to view: SKView) {
         timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.yourFunction), userInfo: nil, repeats: true)
    }

    @objc func yourFunction(){
        print("timer function")
    }

    func goToAnotherScene(){
        timer.invalidate()
    }
}

注意你需要在函数前设置@objc

我建议远离 NSTimer/Timer。 SpriteKit 有它自己的计时功能,让 NSTimer/Timer 无错误地工作是一项巨大的麻烦和任务。使用 SKAction's 来满足 99% 的时间需求。如果您提供代码,我将能够更好地协助您提供正确的答案。