Keyboard Interactivity Within AS3

Keyboard interactivity within the new AS3 environment has changed from its predecessor, AS2. With the changes to the button press in AS3, you’d might expect the Keyboard event calls to receive no easier treatment in how you use them. You’d might even think they are more difficult to integrate and understand, however, personally they seem much easier and simplified to use.

The key difference between Keyboard events within AS3 is consistent event handling of the listeners. In AS2, you would have to create an object within the same level of expected interactivity, then attach it to a new event listener. See Below.

Keyboard Events in AS2

var keyListener:Object=new Object();
keyListener.onKeyDown=function():Void
{
 trace(Key.getCode());
};
Key.addListener(keyListener);

 

Keyboard Events in AS3

stage.addEventListener(KeyboardEvent.KEY_UP,traceKeyPress,false,0,true);
function traceKeyPress(evt:KeyboardEvent):void {
 trace(evt.keyCode);
}

As you can see above, we are basically attaching the Keyboard event listener to the stage so that we can get access to it at all times via runtime. Both examples accompish the same result just with fewer lines of code. Isn’t it lovely!

A mini-example of Keyboard interactivity in AS3

AS3 Keyboard Interactivity ExampleI have taken the liberty of creating a simple example of integrating Keyboard interactivity into a Flash project. The example demonstrates the tracking of the keyboard key codes and checks to see if the up, down, left and right arrows are being pressed.

Download the example .fla

Preview the example .fla

I hope this helps in your migration over into  AS3.  If there is something in particular you want to add or see with the Moving From AS2 to AS3 series, feel free to contact me via the contact page.