How to correctly calculate 1 second with deltaTime in Swift

I am trying to calculate the deltaTime second in deltaTime , but I am not sure how to do this because my deltaTime constantly printing 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 to do this so that I can compress some kind of logic 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 } 
+6
source share
2 answers

I always use SKActions for this type of thing: (written in quick 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) 
+4
source

If you really only need a 1 second interval, you should not store the delta for each frame. Just save the start time and calculate the elapsed time for each frame. When the elapsed time exceeds your 1 second interval, you reset the start time to the present.

  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 } 

Ideally, you need more than 1 timer, so you will need to maintain an array of timers and a table of intervals and blocks for the call. It starts to get very complicated, and in fact, you should probably use the built-in Timer block in iOS 10, which is much more straight forward:

  _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in //Do stuff every second here } 
0
source

Source: https://habr.com/ru/post/1013589/


All Articles