Game Development Reference
In-Depth Information
When the variable is initialized, it contains a
keyDown
variable that contains the value -1. This value
represents that the player
currently is not pressing any key
. When the player presses a key, you have
to store the key code in the variable
Keyboard.keyDown
. You do so by writing an
event handler
that
stores the currently pressed key. Here is what that event handler looks like:
function handleKeyDown(evt) {
Keyboard.keyDown = evt.keyCode;
}
As you can see, the function gets an event as a parameter. That event object has a variable called
keyCode
, which contains the key code of the key the player is currently pressing.
You assign this event-handler function in
Game.start
, as follows:
document.onkeydown = handleKeyDown;
Now, every time the player presses a key, the key code is stored so that you can use it in your
game. But what happens when the player releases the key? The
Keyboard.keyDown
value should be
assigned -1 again, so you know the player currently isn't pressing any key. This is done with the
key up
event handler. Here are the header and body of that handler:
function handleKeyUp(evt) {
Keyboard.keyDown = -1;
}
As you can see, it's very simple. The only thing you need to do is assign the value -1 to the
keyDown
variable in the
Keyboard
object. Finally, you assign this function in
Game.start
:
document.onkeyup = handleKeyUp;
Now you're ready to deal with keypresses in your game. Note that this way of dealing with
keypresses is a bit limited. For example, there is no way to keep track of simultaneous keypresses,
such as the player pressing the A and B keys at the same time. Later, in Chapter 13, you extend the
Keyboard
object to take this into account.
Conditional Execution
As a simple example of how you can use the
Keyboard
object to do something, let's make an
extension of the Painter1 program that draws a colored ball on top of the cannon barrel. By pressing
the R, G, or B key, the player can change the cannon color to red, green, or blue. Figure
6-1
shows a
screenshot of the program.
Search WWH ::
Custom Search