Game Development Reference
In-Depth Information
A crucial piece of information needed is to determine what key was pressed so you can take the appropriate
actions. You can access this by the keyboard event passed into the handler, which holds a reference to the key that
triggered it.
window.onkeydown = moveHero;
function moveHero(e){
alert(e.keyCode + ' was pressed!');
}
It's your job to decipher what key code corresponds with what key and how to react to it. To make this a bit more
readable, creating some string constants for the key codes you need can be worth the setup. Listing 3-10 is an example
of a simple directional pad using the keyboard arrow keys and constants to represent the key codes.
Listing 3-10. Determining Key Pressed by keyCode
const ARROW_KEY_LEFT = 37;
const ARROW_KEY_UP = 38;
const ARROW_KEY_RIGHT = 39;
const ARROW_KEY_DOWN = 40;
window.onkeydown = onDPad;
function onDPad(e){
switch (e.keyCode){
case ARROW_KEY_LEFT:
console.log('move left');
break;
case ARROW_KEY_UP:
console.log('move up');
break;
case ARROW_KEY_RIGHT:
console.log('move right');
break;
case ARROW_KEY_DOWN:
console.log('move down');
break;
}
}
the const keyword is not supported in all browsers, primarily internet explorer. although this keyword is
extremely helpful, you may need to simply declare these values as variables, knowing that the all-caps naming
convention means they should never be altered.
Note
Let's put this to use in an example with a bit more detail. You'll draw a paddle that the player can control with the
arrow keys by moving it left and right along the bottom of the screen (see Listing 3-11).
 
 
Search WWH ::




Custom Search