Key Polling Class

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 we have created the KeyPoll class, which has isDown and isUp methods, each taking a key code as a parameter and returning a Boolean. Using the class looks like this.

package { import flash.display.Sprite; import flash.events.Event; import flash.ui.Keyboard; import bigroom.input.KeyPoll; public class Test extends Sprite { var key:KeyPoll; public function Test() { key = new KeyPoll( this.stage ); addEventListener( Event.ENTER_FRAME, enterFrame ); } public function enterFrame( ev:Event ):void { if( key.isDown( Keyboard.LEFT ) ) { trace( “left down” ); } if( key.isDown( Keyboard.RIGHT ) ) { trace( “right down” ); } } } }

The constructor for the KeyPoll class takes a single parameter which is a DisplayObject on which the object should listen to keyboard events. To listen globally to all keyboard input this should be the stage (as in the example).

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.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply