HTML and CSS Reference
In-Depth Information
The Q.include and Q.extend methods are used to extend Quintus functionality with additional mod-
ules like Sprites and Scenes. To aid in chaining, they also return the Q variable.
Quintus is a method that takes an optional options hash and returns an instance of the engine with a base
level of functionality.
Adding the Game Loop
As you already know, the actual execution of your game from frame to frame is orchestrated by the game loop,
which is responsible for updating the game state and then rendering the current frame of the game on the screen.
The main rendering and JavaScript engine in your browser both run together in a single thread, which means
that you can't use a single tight loop for the game loop as you might in an environment with true multithreading.
Instead, as you saw in the first chapter, your game loop must be run with a timer that cedes control from your
JavaScript code back to the browser, so it can update the page and handle input events.
Building a Better Game Loop Timer
For a long time building a game loop timer was done with the timer functions that have always existed in the
browser: setTimeout and setInterval . Although this worked acceptably to a certain degree, it suffered
from a few drawbacks.
The first drawback was that, especially on slower computers and browsers, the game might try to update the
game more often than the browser could handle, resulting in a visual slow-down. The second drawback was that
even when the browser had a different tab active, the game would continue running at full speed, slowing down
the computer and giving JavaScript games a bad name.
Starting in 2011, browsers began adding support for the requestAnimationFrame API, which allowed
the browser to control the rate at which the game loop was called based on how fast the browser can actually
update the screen. Since it first appeared, the requestAnimationFrame specification has settled out and is
now consistent across the browsers that support it. For browsers that don't support it, Paul Irish (with the help
of a number of other folks on the Internet) developed a polyfill that backports requestAnimationFrame
support to all browsers using setTimeout where necessary. You can see Paul's post on the subject on his blog
from 2011 at http://paulirish.com/2011/requestanimationframe-for-smart-animating/ .
Adding the code from Listing 9-4 to the top of your quintus.js file (outside of the definition for Quin-
tus at the top of the file) can expose a consistent requestAnimationFrame method on the window object
to all browsers.
Listing 9-4: requestAnimationFrame polyfill
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame;
++x) {
window.requestAnimationFrame =
window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
 
 
Search WWH ::




Custom Search