EasyManua.ls Logo

MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH - Page 571

MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH
830 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
Creating interactivity and visual effects 571
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 boldface):
var distance:Number = 10;
this.createTextField("display_txt", 999, 0, 0, 100, 20);
var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
if (Key.isDown(Key.LEFT)) {
car_mc._x = Math.max(car_mc._x - distance, 0);
display_txt.text = "Left";
}
};
Key.addListener(keyListener);
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 boldface):
var distance:Number = 10;
this.createTextField("display_txt", 999, 0, 0, 100, 20);
var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
if (Key.isDown(Key.LEFT)) {
car_mc._x = Math.max(car_mc._x - distance, 0);
display_txt.text = "Left";
} else if (Key.isDown(Key.RIGHT)) {
car_mc._x = Math.min(car_mc._x + distance, Stage.width -
car_mc._width);
display_txt.text = "Right";
} else if (Key.isDown(Key.UP)) {
car_mc._y = Math.max(car_mc._y - distance, 0);
display_txt.text = "Up";
} else if (Key.isDown(Key.DOWN)) {
car_mc._y = Math.min(car_mc._y + distance, Stage.height -
car_mc._height);
display_txt.text = "Down";
}
};
Key.addListener(keyListener);
8.
Select Control > Test Movie to test the file.
For more information about the methods of the Key class, see Key in the ActionScript
2.0 Language Reference.

Table of Contents

Related product manuals