Game Development Reference
In-Depth Information
Handling Keyboard Input Using Arrays
Let's see how you can use arrays to deal with keypresses more efficiently. Because you now have
the ButtonState class, you can use it to handle keyboard input as well and store a ButtonState
instance for each key state. So, in the constructor of Keyboard_Singleton , create an array that
contains all the possible key states, as follows:
this._keyStates = [];
for (var i = 0; i < 256; ++i)
this._keyStates.push(new ButtonState());
Now you can set the down status of a key whenever a key down is detected, as follows:
function handleKeyDown(evt) {
var code = evt.keyCode;
if (code < 0 || code > 255)
return;
if (!Keyboard._keyStates[code].down)
Keyboard._keyStates[code].pressed = true;
Keyboard._keyStates[code].down = true;
}
As you can see, you handle key downs and keypresses just as you did in the case of the mouse
buttons. The following two methods added to Keyboard_Singleton make detecting whether a key is
pressed or down very easy:
Keyboard_Singleton.prototype.pressed = function (key) {
return this._keyStates[key].pressed;
};
Keyboard_Singleton.prototype.down = function (key) {
return this._keyStates[key].down;
};
You don't need the keyboard in the JewelJam game, because all interaction takes place with the
mouse or the touch screen. A later example uses the keyboard once more. This also means you can
basically ignore any keyboard events that occur. If you don't put any keyboard handling in the game-
loop methods, the game completely ignores the player pressing any keys.
Touchscreen Input
Because smartphones and tablets also have a web browser, it's possible to run JavaScript
applications on these devices. Actually, JavaScript is currently the only cross-platform way to
develop applications that run on desktop and laptop machines, mobile phones, and tablets without
having to rewrite the code. For example, you could place the final Painter example on a server and
then access the web page on your tablet. You wouldn't be able to play the game, though, because
you haven't dealt with touch input. In this section, you add the capability of touch input to games.
Fortunately, this is very easy to do in JavaScript!
 
Search WWH ::




Custom Search