【问题标题】:How can you create an NSTimer in a Sprite kit game with Swift?如何使用 Swift 在 Sprite 工具包游戏中创建 NSTimer?
【发布时间】:2017-12-14 01:29:32
【问题描述】:

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

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

但是,当您在 Spritekit 游戏中使用该代码时,它会出现错误并且不起作用。

我可以用什么工作

【问题讨论】:

  • 您遇到什么错误?我在我的 Spritekit 游戏中也使用了计时器,它工作得很好。
  • 你是怎么用的?
  • 主要错误似乎与我的#selector有关。

标签: sprite-kit xcode8 swift4


【解决方案1】:

像这样开始你的计时器:

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

【讨论】:

  • 谢谢,这是我的问题!
  • 仅供参考,如果您离开您的应用程序,此代码将破坏/得到不正确的结果
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-16
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多