Question: How to properly calculate 1 second with deltaTime in Swift


How to properly calculate 1 second with deltaTime in Swift

Answers 2
Added at 2016-12-29 04:12

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) {
                deltaTimeTemp = 0
nr: #1 dodano: 2016-12-29 07:12

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 {
      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
nr: #2 dodano: 2016-12-29 16:12

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

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

let repeatSpawnAction = SKAction.repeatForever(SKAction.sequence([wait, spawnSomething]))
Source Show
◀ Wstecz