Game Development Reference
In-Depth Information
The length of time between updates depends on the hardware being used, the workload of the
system and browser at a given time, and many other variables. Setting a constant ∆T assumes all
these variables are constant. A value of, say 0.25, makes an implicit assumption on the frame
rate in which the game is going to run. Let's say we expect the game to always run at 30 frames
per second (fps), this would make the bike traverse 7.5 edges per second, which is an OK rate.
Running the game now on a slower machine that is only capable of 20 fps will make the bike
travel only five edges per second. The game runs slower that expected and the player gets
bored. On the flip side, running the game on a new machine and possibly a newer browser
capable of 60 fps makes the bike travel 15 edges per second, which is unplayably fast.
Frame rate control
There are several popular ways in JavaScript to establish a more or less constant frame rate. Two of them
use timers and one uses a new capability added to JavaScript with HTML5.
The first option and the one most traditionally used for JavaScript animation is using setTimeout(func,
timeout). This function causes func() to be called approximately timeout milliseconds after the call.
Setting up frame rendering with this function often looks like this:
function main() {
// do some initializations
tick();
}
function tick() {
setTimeout(tick, 16);
// do rendering, animation
}
The main() function starts the animation by making the first call to tick() , which is responsible for
displaying and processing the animation of a single frame of the game. The very first thing that tick()
does is to set up the next call to tick() , 16 milliseconds into the future. A delay of 16 ms between frames
produces a frame rate of approximately 60 fps. When using this method, it is important that the call to
setTimeout() will be performed before any rendering or processing to ensure that the interval between
frames will be as close as possible to 16 ms. The rendering and processing stages of tick() may take a
few milliseconds, and making the setTimeout() call at the end of the function would make the total time of
a single frame longer than 16 ms (see Figure 8-16).
 
Search WWH ::




Custom Search