问题
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