Reacting to User Interaction

So far, all we have done is output the user interaction using a simple trace command. Now we want to expand on that by calling a specific function for each type of user interaction. Specifically, we are going to move a ball around the stage based on the arrow key the user pressed.


Open Key02.fla.

We'll continue building on the file you worked with in the preceding exercise. The changes we will be making here are represented in the Key03.fla file in the Lesson03/Complete folder.


Replace the onKeyDown handler with this script:

  this.onKeyDown = function() {     switch(Key.getCode()) {       case Key.LEFT:         moveLeft();         break;       case Key.RIGHT:         moveRight();         break;       case Key.UP:         moveUp();         break;       case Key.DOWN:         moveDown();         break;     }   }

In this new version of the onKeyDown event handler, we have replaced the trace output calls with calls to specific functions based on the type of user interaction. Now we will look at creating these functions.


Add this script at the end of the current script:

  var SPEED:Number = 5;   function moveLeft():Void {     target._x -= SPEED;   }   function moveRight():Void {     target._x += SPEED;   }   function moveUp():Void {     target._y -= SPEED;   }   function moveDown():Void {     target._y += SPEED;   }

In the first line we are creating a constant variable that represents the number of pixels we will move the target clip each time the function is called.

Each function has specific logic in place to move the target clip. The moveLeft() function moves the target to the left, moveRight() moves it to the right, moveUp() moves it up, and moveDown() moves it down. The _x and _y properties of the movie clip class can be modified to move the clip along the x axis and the y axis. This is pretty straight forward logic.


Choose Control > Test Movie to test the project's functionality so far.

When the movie plays, you will see the red dot in the middle of the stage. When you press the arrow keys, the dot moves in the direction of the arrow you pressed.


Close the test environment to return to the authoring environment and save your work as Key03.fla.

We'll build on this file in the next exercise.

Macromedia Flash 8 ActionScript Training from the Source
Macromedia Flash 8 ActionScript: Training from the Source
ISBN: 0321336194
EAN: 2147483647
Year: 2007
Pages: 221 © 2008-2017.
If you may any questions please contact us: