HTML and CSS Reference
In-Depth Information
Adding in a Step Timer
In Chapter 8 , we created a simple FrameRateCounter object prototype that was used to
display the current frame rate as the game was running. We are going to extend the
functionality of this counter to add in a “step timer.” The step timer will use the time
difference calculated between frames to create a “step factor.” This step factor will be
used when updating the positions of the objects on the canvas. The result will be
smoother rendering of the game objects when there are drops in frame rate, as well as
keeping relatively consistent game play on browsers and systems that cannot maintain
the frame rate needed to play the game effectively.
How the step timer works
We will update the constructor function for FrameRateCounter to accept in a new single
parameter called fps . This value will represent the frames per second that we want our
game to run:
function FrameRateCounter(fps) {
if (fps == undefined){
this.fps = 40
this.fps = fps
If no fps value is passed in, the value 40 will be used.
We will also add in two new object-level scope variables to calculate the step in our
step timer:
this.lastTime = dateTemp.getTime();
this.step = 1;
The lastTime variable will contain the time in which the previous frame completed its
We calculate the step by comparing the current time value with the lastTime value on
each frame tick. This calculation will occur in the FrameRateCounter countFrames()
FrameRateCounter.prototype.countFrames=function() {
var dateTemp = new Date();
var timeDifference = dateTemp.getTime()-this.lastTime;
this.step = (timeDifference/1000)*this.fps;
this.lastTime = dateTemp.getTime();
The local timeDifference value is calculated by subtracting the lastTime value from the
current time (represented by the dateTemp.getTime() return value).
To calculate the step value, divide the timeDifference by 1000 (the number of milli-
seconds in a single second), and multiply the result by the desired frame rate. If the
Search WWH ::

Custom Search