Flash MX Actionscript tutorial - Capturing Key Events

Using Flash MX Pro Actionscript to capture key events such as pressing up and down keys, used in game control for example.

  1. draw a circle, select it and hit F8. give the movie the name of circle
  2. In the instance panel call it circle.
  3. Put this code in the actions window for the circle movie
4.                   onClipEvent(enterFrame){
5.                   if(Key.isDown(Key.LEFT)){
6.                           this._x -=5;
7.                           }
8.                   }
9.            
  1. The code is fairly well self-explanatory. When the left key is down , each time an enterFrame event happens, the movie goes left (in the x direction) -5 pixels.
  2. Finally, Add the extra keys like so :
12.               // go right
13.               onClipEvent(enterFrame){
14.                       if(Key.isDown(Key.RIGHT)){
15.                       this._x +=5;
16.                       }
17.               }
18.               // go down
19.               onClipEvent(enterFrame){
20.                       if(Key.isDown(Key.DOWN)){
21.                       this._Y +=5;
22.                       }
23.               }
24.               // go up
25.               onClipEvent(enterFrame){
26.                       if(Key.isDown(Key.UP)){
27.                       this._y -=5;
28.                       }
29.               }
30.        
  1. now you should be able to control the movement of the circle using the up,down,left,right arrow keys.



Using the Mouse to drag movies

  1. Using the same circle movieclip , delete the former code written above, and enter the following actionscript in the actions panel for the circle:
2.                   onClipEvent(enterFrame){
3.                           this.startDrag(true,0,0,Stage.width, Stage.height);
4.                           this._x = _xmouse;
5.                           this._y = _ymouse;
6.                   }
7.            
  1. The second line allows the dragging of a movie clip within the confines of the stage.
  2. the 3rd and 4th lines give the movie clip the same coordinates as the mouse , thus making the movie follow the mouse around.