Sep
07
2008

What's the best practice to use keyboard in your flash games?

To capture which key was pressed by the user, we use two keyboardEvents KEY_UP and KEY_DOWN. When user presses the key down, KEY_DOWN event is dispatched only once. But what if you want to create a game where to make hero walking or car driving user needs to keep the key down for a longer time. Obviously you don't want user keeps pressing key time after time.

It is a good practice to create boolean variable that would hold the current state of each key. For example if the user keeps the left key, variable called leftPressed will be set to true and your game hero will walk as long as the state of this variable is not changed. And when the user stops pressing the left key, variable changes to false and hero will stop. ENTER_FRAME event listener handler function will be used to move or stop hero according to the current state of the variable.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.Event;
 
public class Keys extends MovieClip
{
   //indicators if left/right keys are pressed or not
   var leftPressed, rightPressed:Boolean = false;
 
   public function Keys()
   {
      //listeners to catch the keyboard events
      stage.addEventListener(KeyboardEvent.KEY_UP, catchKey);
      stage.addEventListener(KeyboardEvent.KEY_DOWN, catchKey);
 
      //status of leftPressed and rightPressed will be checked every frame
      stage.addEventListener(Event.ENTER_FRAME, moveHero);
   }
 
   public function catchKey(e:KeyboardEvent):void
   {
      //checking if key is up or down
      if (e.type == KeyboardEvent.KEY_DOWN)
      {
         if (e.keyCode == Keyboard.LEFT) //37 is the Left key code
            leftPressed = true;
         if (e.keyCode == Keyboard.RIGHT) //39 is the Right key code
            rightPressed = true;
      }
 
      if (e.type == KeyboardEvent.KEY_UP)
      {
         if (e.keyCode == Keyboard.LEFT)
            leftPressed = false;
         if (e.keyCode == Keyboard.RIGHT)
            rightPressed = false;
      }
   }
 
   public function moveHero(e:Event):void
   {
      if (leftPressed)
         hero_mc.x--;
 
      if (rightPressed)
         hero_mc.x++;
   }
}
 

Remember that keybordEvent event listener should reference the stage object.

It is also a good practise to use static constants Keyboard.LEFT, RIGHT, UP and DOWN instead of key codes. Compile-time error will be thrown everytime when you make any typos what wouldn't happened in case that you used only key codes digits. Remember to import flash.ui.Keyboard.

AS3 Tips