HTML and CSS Reference
game is running with no surplus or no deficit in time between frame ticks, the step value
will be 1 . If the current frame tick took longer than a single frame to finish, the value
will be greater than 1 (a deficit). If the current frame took less time than a single frame,
the step value will be less than 1 (a surplus).
For example, if the last frame took too long to process, the current frame will com-
pensate by moving each object a little bit more than the step value of 1 . Let's illustrate
this with a simple example.
Let's say we want the saucer to move five pixels to the right on each frame tick. This
would be a dx value of 5 .
For this example, we will also say that our desired frame rate is 40 FPS. This means that
we want each frame tick to use up 25 milliseconds ( 1000/40 = 25 ).
Let's also suppose that the timeDifference between the current frame and the last frame
is 26 milliseconds. Our game is running at a deficit of 1 millisecond per frame—this
means that the game processing is taking more time than we want it to.
To calculate the step value, divide the timeDifference by 1000 : 26/1000 = .026 .
We multiply this value by the desired fps for our game: .026 * 40 = 1.04
Our step value is 1.04 for the current frame. Because of the deficit in processing time,
we want to move each game object slightly more than a frame so there is no surplus or
deficit. In the case of no surplus or deficit, the step value would be 1 . If there is a surplus,
the step value would be less than 1 .
This step value will be multiplied to the changes in movement vectors for each object
in the update functions. This allows the game to keep a relatively smooth look even
when there are fluctuations in the frame rate. In addition, the game will update the
screen in a relatively consistent manner across the various browsers and systems, re-
sulting in game play that is relatively consistent for each user.
Here are the new movement vector calculations for each object:
player.x += player.movingX*frameRateCounter.step;
player.y += player.movingY*frameRateCounter.step;
tempPlayerMissile.x += tempPlayerMissile.dx*frameRateCounter.step;
tempPlayerMissile.y += tempPlayerMissile.dy*frameRateCounter.step;
tempRock.x += tempRock.dx*frameRateCounter.step;
tempRock.y += tempRock.dy*frameRateCounter.step;