Game Development Reference
In-Depth Information
With
keyCode
, you can find out which physical key was pressed on the keyboard,
and
charCode
is the ASCII code, if there is one.
For example: When key
a
is pressed, you get
keyCode
of 65 and
charCode
of 97.
If the same
a
key pressed with
Caps Lock
on or with the
Shift
key down, you get a
keyCode
of 65 and
charCode
of 65.
As is the case for key
4
in the top row and
$
, the physical key is the same. So in
both cases, you will get a
keyCode
of 52, while the
charCode
is different and is
the corresponding ASCII value of 52 and 36.
For those keys pressed for which there is no ASCII equivalent, for example, function
keys, arrow keys, etc, you get a
charKey
of 0 and
keyCode
as defined in the keyword
class found in
flash.ui
package.
The event also passes in things that are handy such as
altKey
,
ctrlKey,
and
shiftKey
,
which are Boolean values that determine if the corresponding keys were held down
or not when the event was generated. Note that you still get the keyDown and
keyUp events for
Shift
,
Ctrl
, and
Alt
keys just like any other key press.
Arrow key handling: The basics
Often in game programming you handle the movements of a character, vehicle, or
weapon using the arrow keys. The following is a listing to handle the arrow keys that
allows your player to control the corresponding sprite.
The example will create a small circle sprite and put it on the stage. It will set up the
keyboard event handling as demonstrated in the previous example, only that the
callback implementation will handle the arrow keys and discard everything else. We
simply change the x and y of the sprite depending on which arrow key was pressed.
We will also perform some boundary checks so that the sprite does not run off the
stage.
We will also define a constant property called SPEED. The value determines how
fast the sprite should move for each key down. You might think about how you can
make speed a variable and in a game you could change the speed, depending on
whether the player has a certain item to go faster and among other factors.
The following is a full listing, and note the compiler option:
-default-size 500 500 -default-background-color 0xFFFFFF
package {
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;