Screenwriter, Choreographer, Game Developer

Polling the keyboard in Actionscript 3

Posted on

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 is in my GitHub code repository.

Using the class looks like this

  import flash.display.Sprite;
  import flash.ui.Keyboard;
  import net.richardlord.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 KeyPoll 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.

Further, the class clears the key state array when the deactivate event occurs, so key state is not retained if the Flash Player loses focus and stops receiving keyboard input.

Share this post or a comment online -

Also in the collection Actionscript