Creating Interaction with ActionScript > Capturing keypresses

Capturing keypresses

You can use the methods of the predefined Key object to detect the last key the user pressed. The Key object does not require a constructor function; to use its methods, you simply call the object itself, as in the following example:

Key.getCode();

You can obtain either virtual key codes or ASCII values of keypresses:

To obtain the virtual key code of the last key pressed, use the getCode method.
To obtain the ASCII value of the last key pressed, use the getAscii method.

A virtual key code is assigned to every physical key on a keyboard. For example, the left arrow key has the virtual key code 37. By using a virtual key code, you can ensure that your movie's controls are the same on every keyboard regardless of language or platform.

ASCII (American Standard Code for Information Interchange) values are assigned to the first 127 characters in every character set. ASCII values provide information about a character on the screen. For example, the letter "A" and the letter "a" have different ASCII values.

A common place for using Key.getCode is in an onClipEvent handler. By passing keyDown as the parameter, the handler instructs ActionScript to check for the value of the last key pressed only when a key is actually pressed. This movie uses Key.getCode to create navigation controls for the spaceship. You can use the arrow keys to move the spaceship in the movie.

To create keyboard controls for a movie:

1 Decide which keys to use and determine their virtual key codes by using one of these approaches:
See the list of key codes in Keyboard keys and key code values: Overview.
Use a Key object constant. (In the Toolbox list, select Objects, then select Key. Constants are listed in all capital letters.)
Assign the following clip action, then choose Control > Test Movie and press the desired key:
onClipEvent(keyDown) {
	trace(Key.getCode());
}
2 Select a movie clip on the Stage.
3 Choose Window > Actions.
4 Double-click the onClipEvent action in the Actions category of the toolbox.
5 Choose the Key down event in the parameters pane.
6 Double-click the if action in the Actions category of the toolbox.
7 Click in the Condition parameter, select Objects; then select Key and getCode.
8 Double-click the equality operator (==) in the Operators category of the toolbox.
9 Enter the virtual key code to the right of the equality operator.
Your code should look like this:
onClipEvent(keyDown) {
	if (Key.getCode() == 32) {
	}
}
10 Select an action to perform if the correct key is pressed.
For example, the following action causes the main Timeline to go to the next frame when the Spacebar (32) is pressed:
onClipEvent(keyDown) {
	if (Key.getCode() == 32) {
		nextFrame();
	}
}

For more information about the methods of the Key object, see their entries in the ActionScript Dictionary.