User Guide

186 Chapter 6: Creating Interaction with ActionScript
The following procedure shows how to capture keypresses to move a movie clip up, down, left, or
right on the Stage, depending on which corresponding arrow key (up, down, left, or right) is
pressed. The movie clip is confined to an arbitrary area that is 400 pixels wide and 300 pixels
high. Also, a text field shows the name of the pressed key.
To create a keyboard-activated movie clip:
1.
On the Stage, create a movie clip that can move in response to keyboard arrow activity.
In this example, the movie clip instance name is
car.
2.
On the Stage, create a dynamic text box that can update with the direction of the car. Using the
Property inspector, give it an instance name of
display_txt.
Note: Don’t confuse variable names with instance names. For more information, see “About text
field instance and variable names” on page 222.
3.
Select Frame 1 in the Timeline; then select Window > Development Panels > Actions to open
the Actions panel if it is not already visible.
4.
To set how far the car moves across the screen with each keypress, define a distance variable
and set its initial value to 10:
var distance:Number = 10;
5.
To create the event handler for the car movie clip that checks which arrow key (Left, Right, Up,
or Down) is currently pressed, add the following code to the Actions panel:
car_mc.onEnterFrame = function() {
};
6.
To check if the Left Arrow key is pressed and to move the car movie clip accordingly, add code
to the body of the
onEnterFrame event handler. Your code should look like the following
example (new code is in bold):
var distance:Number = 10;
car_mc.onEnterFrame = function() {
if (Key.isDown(Key.LEFT)) {
this._x = Math.max(this._x-distance, 0);
display_txt.text = "Left";
}
};
If the Left Arrow key is pressed, the cars _x property is set to the current _x value minus
distance or the value 0, whichever is greater. Therefore, the value of the _x property can never
be less than 0. Also, the word Left should appear in the SWF file.
7.
Use similar code to check if the Right, Up, or Down arrow key is being pressed. Your complete
code should look like the following example (new code is in bold):
var distance:Number = 10;
car_mc.onEnterFrame = function() {
if (Key.isDown(Key.LEFT)) {
this._x = Math.max(this._x-distance, 0);
display_txt.text = "Left";
} else if (Key.isDown(Key.RIGHT)) {
this._x = Math.min(this._x+distance, 550-this._width);