HTML and CSS Reference
In-Depth Information
Adding a Step Timer
rent frame rate as the game was running. We now extend the functionality of this counter to
add a step timer. The step timer uses the time difference calculated between frames to create a
step factor. This step factor is 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
and relatively consistent game play on browsers and systems that cannot maintain the frame
rate needed to play the game effectively.
Weupdatetheconstructorfunctionfor
FrameRateCounter
toacceptinanewsingleparamet-
er called
fps
. This value represents the frames per second we want our game to run:
function
function
FrameRateCounter
(
fps
) {
iif
(
fps
==
undefined
undefined
){
this
.
fps
=
40
}
else
this
else
{
this
this
.
fps
=
fps
}
If no
fps
value is passed in, the value
40
is used.
We also add two new object-level scope variables to calculate the
step
in our step timer:
this
this
.
lastTime
=
dateTemp
.
getTime
();
this
this
.
step
=
1
;
The
lastTime
variable contains the time in which the previous frame completed its work.
We calculate the
step
by comparing the current time value with the
lastTime
value on each
frame tick. This calculation occurs in the
FrameRateCounter countFrames()
function:
FrameRateCounter
.
prototype
.
countFrames
=
function
function
() {
var
var
dateTemp
=
new
new
Date
();
var
var
timeDifference
=
dateTemp
.
getTime
()
-
this
this
.
lastTime
;
this
this
.
step
=
(
timeDifference
/
1000
)
*
this
this
.
fps
;
this
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).
Tocalculatethe
step
value,dividethe
timeDifference
by
1000
(thenumberofmilliseconds
in a single second) and multiply the result by the desired frame rate. If the game is running