HTML and CSS Reference
In-Depth Information
Much of this code should be familiar from earlier in the chapter. The parts where you grab the canvas ele-
ment and check for a 2d context are straightforward. Next is a call to setupInput() , which is discussed
next. Finally, the game loop starts, and the data for the sprite sheet passes through to SpriteSheet.load .
The next section sets up input:
// Handle Input
var KEY_CODES = { 37:'left', 39:'right', 32 :'fire' };
this.keys = {};
this.setupInput = function() {
window.addEventListener('keydown',function(e) {
if(KEY_CODES[event.keyCode]) {
Game.keys[KEY_CODES[event.keyCode]] = true;
e.preventDefault();
}
},false);
window.addEventListener('keyup',function(e) {
if(KEY_CODES[event.keyCode]) {
Game.keys[KEY_CODES[event.keyCode]] = false;
e.preventDefault();
}
},false);
}
The main point of this block is to add event listeners for keydown and keyup events for those keys that
you care about: specifically the left arrow, the right arrow, and the spacebar. For those events, the listeners trans-
late a numeric Keycode to a friendlier identifier and update a hash called Game.keys to represent the current
state of the user input. The player uses the Game.keys hash to control the ship. For keys used by the game, the
event handlers also call e.preventDefault() , which prevents the browser from performing any default
behavior in response to the key presses. (For the arrow keys and the spacebar, the browser would normally try
to scroll the page.)
One more point about the preceding event handler code: It uses the W3C event model addEventListen-
er method. This code is supported in current versions of the Chrome, Safari, and Firefox browsers, but only
Internet Explorer (IE) versions 9 and above. This is not a huge deal because canvas isn't supported pre-IE9 in
any case, but if you want to add compatibility for older browsers, it's something you need to be careful with.
(The engine built starting in Chapter 9, “Bootstrapping the Quintus Engine Part I,” uses jQuery's on method to
enable easy browser-independent event attachment.)
The last section of the Game class is relatively short:
// Game Loop
var boards = [];
this.loop = function() {
var dt = 30/1000;
for(var i=0, len = boards.length;i<len;i++) {
if(boards[i]) {
boards[i].step(dt);
boards[i] && boards[i].draw(Game.ctx);
}
}
Search WWH ::




Custom Search