Polling the keyboard in Actionscript 3
3rd September 2007
Games often need to get the current state of various keys in order to respond to user input. This is not the same as responding to key down and key up events, but is rather a case of discovering if a particular key is currently pressed.
In Actionscript 2 this was a simple matter of calling Key.isDown() with the appropriate key code. But in Actionscript 3 Key.isDown no longer exists and the only intrinsic way to react to the keyboard is via the key up and key down events.
To rectify this I created the KeyPoll class, which has isDown and isUp methods, each taking a key code as a parameter and returning a Boolean. The class and an example of its use are on the Flash Game Code site.
The class uses a ByteArray to hold the current keyboard state, which is updated in response to Keyboard events and queried by the public methods, isDown and isUp. Using a ByteArray is more compact than using an Array of Booleans, and in tests it also turned out to be marginally faster, although the difference in speed was not significant enough to matter.
Postscript
4th September 2007
Today I was notified of an error in the class which I have fixed. If you previously downloaded the class you’ll want the new version which is on the Flash Game Code site.
Read more articles about Game Development, Actionscript 3

Comments closed.