Internet / Software Applications

Macromedia Flash MX 2004 ActionScript Programming Tutorial

Using the getCode() Method to Catch Key Presses

Given the fact that asteroids are going to be coming from random positions across the top of the stage, our gun as it is now won’t do the user much good. We need to give the user the ability to move the gun. We can add some simple functionality using the built-in properties of the Key object to move the gun from left to right and back, similar to the old Atari games:

  1. Delete the on(keyPress) event handler from the gun_mc movie clip, along with all its code. We’re going to incorporate the space bar key press into the code that checks for other key presses, specifically the LEFT and RIGHT arrow keys.
  2. Add an onClipEvent(enterFrame) event handler to the gun_mc movie clip, with the following code:

onClipEvent(enterFrame) {

//Determine which key is pressed

var whichKey = Key.getCode();

//move the gun

switch (whichKey) {

case Key.LEFT:

_x -= 25;

break;

case Key.RIGHT:

_x += 25;

break;

case Key.SPACE:

_root.numShots++;

this.attachMovie(“laser_mc”, “laser_mc” + _root.numShots, _root.numShots);

break;

}

}

The first line uses the getCode() method to assign the constant associated with a key to the variable whichKey. We then use a switch statement to check the value of whichKey—the constant associated with whatever key on the keyboard is being pressed. When you type in your case clauses, you’ll see the pop-up menu after you type “Key.” The pop-up menu lists the Key class’s properties, which include keys that each have associated constants.

The first case clause moves the x (horizontal) position of the gun_mc movie clip 25 pixels to the left. This happens if the user presses the LEFT arrow key. The second case clause moves the x position of the movie clip 25 pixels to the right. The third responds to the user pressing the space bar, which increments our numShots variable and attaches a duplicate of the “laser_mc” movie clip from the library, effectively firing the gun.

  1. Save the movie. If you test it now, you’ll notice a problem with the movement of the gun. Once you press a left or right arrow key, the gun starts moving—and doesn’t stop until you press a different key. We need to add a way to detect whether or not the user has released the key, to stop the movement of the gun. We’re going to do this in the next section, using a listener.