Keyboard Event - Calculate KeyCode Values

Keyboard Event - Calculate KeyCode Values

Flash CS4 ActionScript 3.0 Tutorial


How to Determine the KeyCode Value for a Specific Keyboard Key with Flash ActionScript



Moving objects with a keyboard press is often used in Flash games. For instance, you may wish to move a spaceship left or right by pressing the left or right arrow keys on the keyboard.

In addition to the arrow keys, you can assign also events to other keys.

In this example we will illustrate how to create a Keyboard event that triggers a function. The function will display the KeyCode value in the Output panel each time a key is pressed. Once you determine the KeyCode, it can be used in a Keyboard Event.

For more information on Keyboard Events, see topic, Keyboard Press - Move Object.


Step One

Open a new document and add a new layer.

Step Two

Name the top layer Actions and the lower one Content.

Step Three

Click the first frame of the Content layer and add a rectangle to the stage.

Step Four

Click the rectangle and press F8 to convert it to a Movie Symbol.

Step Five

Select the rectangle and assign it an instance name of moveBox_mc in the Properties panel.

Step Six

Open the ActionScript panel for your keyframe in the Actions layer by Option double-clicking (PC - Alt double-clicking) the keyframe.

Step Seven

Copy/Paste the following code in the ActionScript Panel:

stage.addEventListener(KeyboardEvent.KEY_DOWN, onClick01);

function onClick01(e:KeyboardEvent):void {






Step Eight

Click the Auto Format button to format the code

Step Nine

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Choose Control > Disable Keyboard Shortcuts in the SWF Player window. Press various keys on the keyboard and note the KeyCode assigned to each key in the Output panel. If you press the right arrow, the box moves 10 pixels to the right. This occurs because the keycode for the right arrow is 39.

Dissecting the Code

The first line of the code at Step Seven adds an event listener to the stage. Whenever any key is clicked, the onClick01 function is triggered.

The next lines of code define the function. The function displays the keyCode for the current key press in the Output panel.

The second half of the function tests to see if keyCode 39 is pressed. This is the right arrow key. Once the right arrow is pressed, the box moves 10 pixels to the right.

KeyCode Values

In addition to describing the key with a number (i.e., 39), you can use pre assigned words for specific keys. For instance, if you substitute Keyboard.LEFT for 37 and Keyboard.RIGHT for 39 (in the if statement), you will get the same results. For more information, see topic Keyboard Press - Move Object.