Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly calculate 1 second with deltaTime in Swift

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
            }
like image 972
tbaldw02 Avatar asked Dec 29 '16 03:12

tbaldw02


People also ask

Is time deltaTime a method?

Time. deltaTime is simply the time in seconds between the last frame and the current frame. Since Update is called once per frame, Time. deltaTime can be used to make something happen at a constant rate regardless of the (possibly wildly fluctuating) framerate.

How do I get the difference between two times in Swift?

To calculate the time difference between two Date objects in seconds in Swift, use the Date. timeIntervalSinceReferenceDate method.

What is the use of time deltaTime?

deltaTime is the completion time in seconds since the last frame. This helps us to make the game frame-independent. That is, regardless of the fps, the game will be executed at the same speed.

How do I get deltaTime?

It is done by calling a timer every frame per second that holds the time between now and last call in milliseconds. Thereafter the resulting number (delta time) is used to calculate how far, for instance, a video game character would have travelled during that time.


1 Answers

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)
like image 53
claassenApps Avatar answered Oct 25 '22 00:10

claassenApps