How to properly calculate 1 second with deltaTime in Swift

别说谁变了你拦得住时间么 提交于 2019-12-05 08:16:18

I always use SKActions for this type of thing: (written in swift 3)

let wait = SKAction.wait(forDuration: 1.0)
let spawnSomething = SKAction.run {
   //code to spawn whatever you need
}

let repeatSpawnAction = SKAction.repeatForever(SKAction.sequence([wait, spawnSomething]))

self.run(repeatSpawnAction)

If you really only care about a 1 second interval then you should not be storing the delta for every frame. Just store the start time and calculate the elapsed time each frame. When the elapsed time exceeds your 1 second interval then you reset the start time to now.

  override func update(_ currentTime: CFTimeInterval) {
      let elpasedTimeSinceLastupdate = currentTime - startTime
      //Check if enough time has elapsed otherwise there is nothing to do
      guard elpasedTimeSinceLastupdate > requiredTimeIntervale else {
        return
      }
      startTime = currentTime
      // Do stuff here
  }

I ideally you want more than 1 timer, so then you would need to maintain an array of timers and a table of intervals and blocks to call. This starts to get very complicated and really you should probably just use the built in block Timer in iOS 10, which is much more straight forward:

    _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in
        //Do stuff every second here
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!