HTML and CSS Reference
In-Depth Information
Creating the Game Object
The main game object is a one-off object called, perhaps not surprisingly, Game . Its main purpose is to initialize
the game engine for Alien Invasion and run the game loop as well as provide a mechanism for changing the
main scene that displays.
Because Alien Invasion doesn't have an input subsystem, the Game class is also responsible for setting up
listeners for keyboard and touch input. To start, only keyboard input is handled; touch input is added in the next
chapter.
Now that the game starts to take shape, a few additional considerations are necessary. Instead of just execut-
ing code willy-nilly when it is evaluated, it generally makes sense to wait for the page to finish downloading
before initializing the game. The Game class takes this into consideration and listens for a “load” event from
the window before booting up the game.
The code for the Game class will be added at the top of engine.js .
Implementing the Game Object
Now walk through the 40+ lines of code that make up the Game object a section at a time. (See the full listing at
the top of game_class/engine.js in the chapter code.) The class starts off much like the SpriteSheet ,
as a one-time class instance:
var Game = new function() {
Next is the initialization routine, called with the ID of the canvas element to fill, the sprite data that is passed
to the SpriteSheet , and the callback when the game is ready to start.
// Game Initialization
this.initialize = function(canvasElementId,sprite_data,callback) {
this.canvas = document.getElementById(canvasElementId);
this.width = this.canvas.width;
this.height= this.canvas.height;
// Set up the rendering context
this.ctx = this.canvas.getContext && this.canvas.getContext('2d');
if(!this.ctx) { return alert("Please upgrade your browser to
play"); }
// Set up input
this.setupInput();
// Start the game loop
this.loop();
// Load the sprite sheet and pass forward the callback.
SpriteSheet.load(sprite_data,callback);
};
Search WWH ::




Custom Search