Game Development Reference
In-Depth Information
sible. Now, imagine running this 8 MHz-designed game on a modern processor
that is hundreds of times faster. The game would be over before you even blinked!
In other words, if the preceding enemy movement pseudocode were run 30 times
per second (30 FPS), the enemy would move a total of 150 pixels in one second.
However, at 60 FPS, the enemy would move a total of 300 pixels during that same
period of time. To solve this issue, we need to introduce the concept of delta time :
the amount of elapsed game time since the last frame.
In order to convert the preceding pseudocode to use delta time, we need to think of
the movement not in terms of pixels per frame, but in terms of pixels per second.
So if the ideal movement speed is 150 pixels per second, this pseudocode would
be preferable:
Click here to view code image
// Update x position by 150 pixels/second
enemy.position.x += 150 * deltaTime
Now the code will work perfectly fine regardless of the frame rate. At 30 FPS, the
enemy will move 5 pixels per frame, for a total of 150 pixels per second. At 60
FPS, the enemy will only move 2.5 pixels per frame, but that will still result in a
total of 150 pixels per second. The movement certainly will be smoother in the 60
FPS case, but the overall per-second speed will be identical.
As a rule of thumb, whenever an object in the game world is having its properties
modified in a way that should be done over the course of several frames, the modi-
fication should be written as a function of delta time. This applies to any number
of scenarios, including movement, rotation, and scaling.
But how do you calculate what the delta time should be every frame? First, the
amount of real time that has elapsed since the previous frame must be queried.
This will depend greatly on the framework, and you can check the sample games
to see how it's done in a couple of them. Once the elapsed real time is determined,
it can then be converted to game time. Depending on the state of game, this may
be identical in duration or it may have some factor applied to it.
This improved game loop would look something like what's shown in Listing 1.2 .
Listing 1.2 Game Loop with Delta Time
Click here to view code image
Search WWH ::




Custom Search