AS2 → AS3: Using Keyboard Events

Download Example Files

Using the keys on your keyboard to interact with the Flash environment has changed from AS2 to AS3. While some of the AS3 code takes a couple of more lines than the AS2 stuff to get done, this is not the case with this example. The AS3 code is not only shorter but way more elegant and easier to implement.

The old AS2 way had you create a listener object and add a listener to the Key class. This looked similar to the following:

Actionscript:
  1. var keyListener:Object = new Object();
  2.  
  3. keyListener.onKeyDown = function():Void
  4. {
  5.     trace(Key.getCode());
  6. };
  7.  
  8. Key.addListener(keyListener);

In AS3, all you have to do is add a listener to your stage. Here it is:

Actionscript:
  1. stage.addEventListener(KeyboardEvent.KEY_UP, traceKey, false, 0, true);
  2.  
  3. function traceKey($evt:KeyboardEvent):void
  4. {
  5.     trace($evt.keyCode);
  6. }

As I've progressed over the past year into more and more AS3 development I simply despise doing things the old AS2 way. When I have to work on an AS2 project these days I loathe opening up Flash and doing the programming.

If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.

4 Comments

question, I've been trying this in some other demos I wrote but for some reason all the keys don't post a key code back in the trace. but if you trace just the event it works. any ideas?

Corban,
Make sure that when you test your movie you go to Control > Disable Keyboard Shortcuts so that all the keys on the keyboard will register their appropriate key codes.

I should also point out that this is only when testing in the Flash IDE. when in a browser it will read the key codes as expected.

The AS2 way is more shorter (if you handle it the same way you did in AS3)

Key.addListener(this);
function onKeyUp():Void
{
trace(Key.getCode());
}

Leave a comment

(required)

(required)