3D Game Programming

(C. Jardin) #1
// Listen for keypress events
document.addEventListener('keydown',function(event) {
alert(event.keyCode);
});

This adds an event listener to the entire page. It listens for keydown events.
When our code notices a keydown, it will alert us with the keycode of the event
that just occurred.

What is a keycode? To answer that, let’s try it out! Click the Hide Code button
in the toolbar at the top of the page, then press the A key on your keyboard.
You should see something like this alert dialog.

What is this 65? Keep in mind that computers store everything, even letters,
as numbers. The computer converts that number into a letter when displaying
the correct letter to us humans. When we think of the letter a, a computer is
thinking 65.

Why do we need to know this? Click the OK button on the alert if you haven’t
already done so. Then repeat for the left, up, right, and down arrow keys on
your keyboard. For the left arrow, you should discover that the computer
thinks 37. For the up arrow, the computer thinks 38. For the right arrow, the
computer detects the key as 39. For the down arrow, the computer thinks 40.

Let’s use those keycodes to move our avatar!


4.3 Converting Keyboard Events into Avatar Movement


By playing with the keyboard event listener, we now know the numbers that
correspond to each of the four arrow keys. We convert those arrow keys and
numbers into avatar movement like this:

Arrow Key Computer Number Avatar Direction
Left 37 Left
Up 38 Forward
Right 39 Right
Down 40 Back

report erratum • discuss

Converting Keyboard Events into Avatar Movement • 37


Prepared exclusively for Michael Powell

Free download pdf