Game Development Reference
In-Depth Information
p.handleKeyDown = function (e) {
e = !e ? window.event : e;
switch (e.keyCode) {
case ARROW_KEY_LEFT:
this.leftKeyDown = true;
break;
case ARROW_KEY_RIGHT:
this.rightKeyDown = true;
break;
case ARROW_KEY_UP:
this.upKeyDown = true;
break;
case ARROW_KEY_DOWN:
this.downKeyDown = true;
break;
}
}
p.handleKeyUp = function (e) {
e = !e ? window.event : e;
switch (e.keyCode) {
case ARROW_KEY_LEFT:
this.leftKeyDown = false;
break;
case ARROW_KEY_RIGHT:
this.rightKeyDown = false;
break;
case ARROW_KEY_SPACE:
this.spawnHeroBullet();
break;
case ARROW_KEY_UP:
this.upKeyDown = false;
break;
case ARROW_KEY_DOWN:
this.downKeyDown = false;
break;
}
}
Notice the use of the native JavaScript method bind . This is used to set the event handler's scope. These event
handlers should look very familiar. The global constants for the key codes are used to detect the key pressed. The
arrow keys will set the proper game properties to true when the key is pressed down and back to false when they are
released. These values are evaluated during the update cycle to determine if and where the hero should be placed
in the next render cycle. The space bar, which will fire a bullet, is only evaluated in the handleKeyUp handler. This
is done so the player needs to release the key to fire, instead of a constant rapid fire that would occur when holding
down the spacebar.
Search WWH ::




Custom Search