I have written a small class that enables programmers to access which keys are pressed at any given time. Its particularly useful for game development when you want to move a sprite every frame for example.
The class is pretty simple and also quite small. The class contains an 2 dimensional array, and when the KEY_DOWN listener is fired the Key Code is stored into the array and a Boolean for that Key Code set to true. When the KEY_UP listener is fired, the Boolean relating to that Key Code is set to false.
To keep it simple, to use the KeyManager all you need to do is pass it an instance on the stage using an init method. As all the public methods are static, this can be done by:1
To find out if a key has been pressed, you simply pass through a Key Code to the isKeyDown method. Fortunately, the Adobe libraries come with a list of Key Codes which can be found in the flash.ui.Keyboard class. We can use these with the KeyManager to easily access if a key has been pressed , like so :1
If the key has been pressed, the KeyManager will return true, else false. It is a pretty quick and easy way to work with the keyboard.
Here is the full code listing for the KeyManager:
To demonstrate using the KeyManager, I have made a small application which shows the keyboard manager being used to control a small car. I am currently writing a tutorial on the physics and techniques used to create the car, but in the meantime I have commented each line and uploaded a ZIP folder of the files. You can download it here:
The project is a Flash Builder project, but it should work with an FLA too if you set the Document class to TopDownCarExample.as and save the FLA in the src folder.