Inside my scene, I have overridden the default -(void) update: (CFTimeInterval) currentTime
function. It is worth noting that the currentTime
variable is actually the elapsed time since the beginning of a presumably arbitrary system time, as opposed to the elapsed time since last frame. This update function runs through all of my characters and applies their movement based on velocity per second and elapsed time since last update in seconds. The usual way to get the elapsed time since last update in seconds is to have an NSTimeInterval in your class that stores the last update, and subtract the last update time from the current update time, getting elapsed seconds. However, the initial elapsed time is NOT zero. As such, subtracting zero from a very large number produces a perceived elapsed time of many tens of thousands of seconds. As such, any characters already in motion on the very first frame will have moved very far away.
The obvious solution to this would be to initially set the last update time to the initial time elapsed. However, I do not see any method to access this within SKScene
, or more specifically within -(void) didMoveToView: (SKView *) view
.
Another solution would be to set the initial CFTimeInterval to a negative number, such as -1
. Then, one would check each update function whether the time is -1
. If so, one would set the elapsed time since last update to 0
, otherwise one would do the ordinary elapsedTime = currentTime - lastUpdate
. However, doing this if statement every single update function seems messy and unneeded.
Are there any other ways of finding this elapsed time since last update accurately?
You're right that checking for a flag every iteration is wasteful, so it's a question of what's the most efficient solution.
I would think the best (read: most efficient) solution would be to not apply any changes in the first update
besides simply saving the currentTime variable. This shouldn't affect your gameplay at all; nobody will notice the frame has been dropped. You could do it by saving a pointer to a function, calling that function in the first iteration of update
which will also change the pointer to another function, and then update
will call the second function from that point onward.
The method I think you're looking for is CFAbsoluteTimeGetCurrent
, but SK's update
method tends to hand back a different, earlier time, likely due to the amount of time taken to pass the time into update
versus just using CFAbsoluteTimeGetCurrent
. If you're OK with a little extra overhead without using an if
, disregard currentTime
and always use CFAbsoluteTimeGetCurrent
in your update
method.
Then again, if you're worried about the overhead of a single if
statement in each frame, you wouldn't be using a framework. 60 if
s per second is trivial work for even the slowest mobile processor anyway.