Keyboard Press - Move Object

Keyboard Press - Move Object

Flash CS4 ActionScript 3.0 Tutorial

 

How to Move an Object with a Key Press on the Keyboard 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.

For more information on other types of Events, see topics, Enter Frame Event - Rotate Object at Current Frame Rate, Mouse Event - Drag Object, Mouse Event - Hide Object and Timer Event - Count a Number.

Tutorial Elements

Movie Symbol with instance name of oval_mc

 

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 an oval object to the stage.

Step Four

Select the oval object and press F8 to convert it to a Movie Symbol.

Step Five

With oval Movie Symbol selected, assign it an instance name of oval_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 {

if (e.keyCode==Keyboard.RIGHT) {

oval_mc.x+=10;

}else if(e.keyCode==Keyboard.LEFT){

oval_mc.x-=10;

}

}

Step Eight

Click the Auto Format button to format the code

Step Nine

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Each time you press the right arrow key, the, the oval object moves 10 pixels to the right. By pressing the left arrow key, the oval moves 10 pixels to the left.

Dissecting the Code

The first line of the code at Step Nine 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 checks to see if the right arrow is pressed. If true, the oval object moves 10 pixels to the right.

If the left arrow is pressed, the oval moves 10 pixels to the left.

KeyCode Values

In addition to describing the key with words (i.e., Keyboard.RIGHT), you can use pre assigned numbers for specific keys. For instance, if you substitute 37 for Keyboard.LEFT and 39 for Keyboard.RIGHT, you will get the same results. For more information, see topic Keyboard Event - Calculate KeyCode Values.