Game Development Reference
In-Depth Information
You use the
||
operator here to determine which method the
window.requestAnimationFrame
name
refers to. If the first option isn't defined (for example, if you're dealing with an older browser), you
check any of the older names. If none of the optimized game-loop methods are available, you let
requestAnimationFrame
point to a function that calls the
window.setTimeout
method. In JavaScript,
the
window
variable is a container of the global namespace. This means that you can call the
requestAnimationFrame
method with or without the
window
variable in front of it. The call:
window.requestAnimationFrame(callbackFunction);
is equivalent to
requestAnimationFrame(callbackFunction);
The Painter3 example uses the optimized game-loop method to run the asset-loading loop as well
as the game loop, as follows:
Game.assetLoadingLoop = function () {
if (Game.spritesStillLoading > 0)
window.requestAnimationFrame(Game.assetLoadingLoop);
else {
Game.initialize();
Game.mainLoop();
}
};
And similarly, here is the
mainLoop
method in the
Game
object:
Game.mainLoop = function () {
Game.handleInput();
Game.update();
Game.draw();
Mouse.reset();
window.requestAnimationFrame(Game.mainLoop);
};
Browsers handling things differently is a major challenge for JavaScript developers, even though a
lot of progress has been made toward standardization of how browsers execute JavaScript code.
When you develop JavaScript games, you'll probably encounter these differences in browsers at
some point. Therefore, always test your game on the most common browsers before releasing it!
Separating Generic Code from Game-Specific Code
Previously, you haven't made any distinction between code that can be used for many different
games and code that is specific to a single game. Some parts of the code that you've written, such
as the
Game.mainLoop
method, would probably be useful for other JavaScript games as well. The
same goes for all the code you've written to load sprites. Now that you've seen a way to split code
over different script files, you can use that to your advantage. By splitting generic code from code
that is specific to Painter, it will be easier to reuse that generic code later. If you would like to reuse
Search WWH ::
Custom Search