HTML and CSS Reference
In-Depth Information
The FrameRateCounter Object Prototype
Arcade games such as
Asteroids
and
Geo Blaster Basic
rely on fast processing and screen
updates to ensure all game-object rendering and game-play logic are delivered to the
player at a reliable rate. One way to tell whether your game is performing up to par is
to employ the use of a frame rate per second (FPS) counter. Below is a simple one that
can be reused in any game you create on the canvas:
//*** FrameRateCounter object prototype
function FrameRateCounter() {
this.lastFrameCount = 0;
var dateTemp = new Date();
this.frameLast = dateTemp.getTime();
delete dateTemp;
this.frameCtr = 0;
}
FrameRateCounter.prototype.countFrames=function() {
var dateTemp = new Date();
this.frameCtr++;
if (dateTemp.getTime() >=this.frameLast+1000) {
ConsoleLog.log("frame event");
this.lastFrameCount = this.frameCtr;
this.frameLast = dateTemp.getTime();
this.frameCtr = 0;
}
delete dateTemp;
}
Our game will create an instance of this object and call the
countFrames()
function on
each frame tick in our
update()
function. We will write out the current frame rate in
our
render()
function.
Example 8-11
shows these functions by adding code to
Example 8-10
. Make sure you
add the definition of the
FrameRateCounter
prototype object to the code in
Exam-
ple 8-10
under the
canvasApp()
function but before the final
<script>
tag. Alternatively,
you can place it in its own
<script\>
tags, or in a separate
.js
file and set the URL as the
src=
value of a
<script>
tag. For simplicity's sake, we will keep all our code in a single
file.
Example 8-11
contains the definition for our
FrameRateCounter
object prototype, as
well as the code changes to
Example 8-10
that are necessary to implement it.
Example 8-11. The FrameRateCounter is added
function update() {
x = x+movingX;
y = y+movingY;
frameRateCounter.countFrames();
}