MACROMEDIA FLASH MX 2004-USING ACTIONSCRIPT IN FLASH Use Manual page 186

Using actionscript in flash
Hide thumbs Also See for FLASH MX 2004-USING ACTIONSCRIPT IN FLASH:
Table of Contents

Advertisement

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:
On the Stage, create a movie clip that can move in response to keyboard arrow activity.
1.
In this example, the movie clip instance name is
On the Stage, create a dynamic text box that can update with the direction of the car. Using the
2.
Property inspector, give it an instance name of
Note: Don't confuse variable names with instance names. For more information, see
field instance and variable names" on page
Select Frame 1 in the Timeline; then select Window > Development Panels > Actions to open
3.
the Actions panel if it is not already visible.
To set how far the car moves across the screen with each keypress, define a
4.
and set its initial value to 10:
var distance:Number = 10;
To create the event handler for the car movie clip that checks which arrow key (Left, Right, Up,
5.
or Down) is currently pressed, add the following code to the Actions panel:
car_mc.onEnterFrame = function() {
};
To check if the Left Arrow key is pressed and to move the car movie clip accordingly, add code
6.
to the body of the
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 car's _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.
Use similar code to check if the Right, Up, or Down arrow key is being pressed. Your complete
7.
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);
186
Chapter 6: Creating Interaction with ActionScript
event handler. Your code should look like the following
onEnterFrame
.
car
.
display_txt
222.
"About text
variable
distance

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the FLASH MX 2004-USING ACTIONSCRIPT IN FLASH and is the answer not in the manual?

Questions and answers

This manual is also suitable for:

Flash mx 2004 - actionscript

Table of Contents