Keyboard events are finicky, and AS3 is no exception. They work like regular keyboard strokes anywhere else on your system. Press a key once, and it fires once, but keep it held down and after a short delay it fires repeatedly at a system defined interval. This is how keyboard events should work for text editing, but it does not suffice for something like controlling movement in a game. This is why I developed a class to better handle events for situations like these.
This class extends the EventDispatcher class. It accepts 4 arguments in the constructor but has only one required argument, the InteractiveObject that will be dispatching the events from the keyboard. A note: This object must have the stage’s focus to dispatch keyboard events. I did not build in the focus management functionality within this class, because it should be managed elsewhere. If you want to listen to global keyboard events just pass in the stage as the first argument.
Here is an example of the KeyboardControl class in action:
[swfobj src=”https://jidd.jimisaacs.com/files/2008/11/example-KeyboardControl.swf” width=”400″ height=”150″ align=”center” required_player_version=”10.0.0″]
AS3 KeyboardControl Example
This class uses the KeyboardControlEvent class, within this class are 4 important types:
- KeyboardControlEvent.KEY_UP
- KeyboardControlEvent.KEY_DOWN
- KeyboardControlEvent.ANY
- KeyboardControlEvent.key()
These events have some familiar types that react differently, and some new types. The KEY_UP, and the KEY_DOWN types are dispatched only once regardless of how many keys are pressed or released in a given action. This means if the left arrow is pressed and held, KEY_DOWN is dispatched, then if the right arrow is pressed and held KEY_DOWN is not dispatched, then if the left arrow is released but the right arrow remains held, KEY_UP is not dispatched, then finally when the right arrow is released KEY_UP is dispatched.
The ANY event type and the key() method are for listening to keyCodes themselves. The ANY type is dispatched for any key that is pressed, and for the entire time (at a specified interval) that the key is down. The key() method converts any normal keyCode to a KeyboardControlEvent type. So you can add a listener to any particular keyboard key.
Now here is the actual class that controls keyboard events more appropriately for game controls, enjoy 😉
com.jimisaacs.keyboard.KeyboardControl
Comment if you have any questions, or suggestions.
Leave a Reply