代码之家  ›  专栏  ›  技术社区  ›  Nathan C

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

  •  0
  • Nathan C  · 技术社区  · 6 年前

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

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

    但是,当您在 Spritekit游戏 ,它会出现错误并且不起作用。

    我能用它做什么 作品 ?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Marcel    6 年前

    只需按如下方式启动计时器:

    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
  •  0
  •   Knight0fDragon    6 年前

    我建议远离N定时器/定时器。SpriteKit有自己的计时功能,让NSTimer/Timer无bug工作是一件非常麻烦的事情。使用 SKAction's 满足99%的计时需求。如果您提供代码,我将能够更好地帮助您找到正确的答案。