Game Development Reference
In-Depth Information
have put in the following code changes, it will appear that we are only rotating the player, but we
will be setting the groundwork for moving the player about the maze.
Adding the keypress logic
The first code change is very simple. We need to add a variable to hold keypress values.
Keypresses will be handled with simple key up and down events. When a key is pressed down,
the Boolean
true
will be placed in an array called
keyPressList
(at the array index location
represented by the ASCII key value)
when a key up event is encountered, a
false
will be placed
at the array index location. So, for instance, when the user presses down, the key code number
37
is sent to the event listener for key down events. That listener will then place
true
in the
keyPressList[37]
location. Let's check out the code changes necessary to get this working.
First, in the variable definition section, add in a line for the
keyPressList
variable:
//iteration#2 variables, moving the player around the maze
private var keyPressList:Array = [];
The only changes to the
newGame
function are the addition of
KEY_DOWN
and
KEY_UP
event listeners:
private function newGame():void {
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpListener);
newLevel();
}
These two completely new listener functions must be added to the file:
private function keyDownListener(e:KeyboardEvent):void {
trace(e.keyCode);
keyPressList[e.keyCode]=true;
}
private function keyUpListener(e:KeyboardEvent):void {
keyPressList[e.keyCode]=false;
}
Testing iteration 2
You will want to comment out the
trace("run game");
statement in the
runGame
function to be
able to see the key events in the output. If you run the code and press each of the arrow keys,
you will see output like this:
38
40
39
37
The 38, 40, 39, and 37 represent pressing each of the arrow keys.