How to properly calculate 1 second with deltaTime in Swift

…衆ロ難τιáo~ 提交于 2019-12-07 03:03:11

问题


I'm trying to calculate an elapsed second in deltaTime but I'm not sure how to do it, because my deltaTime constantly prints 0.0166 or 0.0167.

Here is my code:

override func update(_ currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */

    deltaTime = currentTime - lastTime
    lastTime = currentTime

How do I make it so I can squeeze some logic in here to run every second?

EDIT: I was able to come up with the following, but is there a better way?

            deltaTimeTemp += deltaTime
            if (deltaTimeTemp >= 1.0) {
                print(deltaTimeTemp)
                deltaTimeTemp = 0
            }

回答1:


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)



回答2:


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
    }


来源:https://stackoverflow.com/questions/41372854/how-to-properly-calculate-1-second-with-deltatime-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!