What's the best practice to use keyboard in your Flash games?
To capture which key was pressed by a user, we use two keyboardEvents - KEY_UP and KEY_DOWN. When a user presses the key down, KEY_DOWN event is dispatched only once. But if you want to create a game where to make a hero walking or a car driving user needs to keep a key down for a longer time. Obviously you don't want a 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 a 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 |
import flash.display.MovieClip; |
Remember that the 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 the key codes. A 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.

