Task: Keyboard-Controlled Movie Clip

I l @ ve RuBoard

Let's use our knowledge of testing the keys on the keyboard to allow the user to move a movie clip around the screen.

  1. Start with a new movie.

  2. Create a simple movie clip. A simple shape such as a circle will do.

  3. Attach this script to it:

     onClipEvent(enterFrame) {     if (Key.isDown(Key.LEFT)) this._x -= 5;     if (Key.isDown(Key.RIGHT)) this._x += 5;     if (Key.isDown(Key.UP)) this._y -= 5;     if (Key.isDown(Key.DOWN)) this._y += 5; } 

    All that this script does is test each of the four arrow keys and send the movie clip a little in that direction if the key is pressed.

  4. Now replace that script with one that is a little more ready for future use. This script stores the starting location of the movie clip in x and y . It also sets the speed variable to 5.

    In Every frame that goes by, it tests the four arrow keys but adjusts the x and y variables instead of directly adjusting the location of the movie clip. It uses speed as its adjustment amount. Then it sets the location to x and y :

     onClipEvent(load) {     x = this._x;     y = this._y;     speed = 5; } onClipEvent(enterFrame) {     if (Key.isDown(Key.LEFT)) {         x -= speed;     }         if (Key.isDown(Key.RIGHT)) {         x += speed;     }         if (Key.isDown(Key.UP)) {         y -= speed;     }         if (Key.isDown(Key.DOWN)) {         y += speed;     }     this._x = x;     this._y = y; } 

    This longer script has two advantages. First, because we are adjusting variables rather than the real location, we can test the new location before making the move. This will come in handy in games where you don't want the object to be seen outside a certain area. Second, this script makes it easy to adjust the speed since it is in one place only.

    Because we use speed instead of repeating the number 5 four times, we have one central place where we can adjust the speed of the movie clip.

I l @ ve RuBoard

Sams Teach Yourself Flash MX ActionScript in 24 Hours
Sams Teach Yourself Flash MX ActionScript in 24 Hours
ISBN: 0672323850
EAN: 2147483647
Year: 2002
Pages: 272

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net