Detecting key combinations

Actionscript 3 introduced a new system of events for dealing with when the user interacts with our applications. This system came in the form of InteractiveObjects and the various events that they broadcast. InteractiveObjects are what the user interacts with (go figure?). Interaction comes in a few flavors: mouse clicks, key presses, focus and tabbed. I’m not going to get into detail about any of these, we are going to talk about how we usually handle basic interactions and how to introduce a method for detecting key combinations that makes sense.

InteractiveObjects cannot be instantiated. They are instead integrated as part of the display api, which makes perfect sense.

Generally when you are listening for the usual interactions, such as key presses and mouse clicks, this is how it would go:

..

   addEventListener( MouseEvent.CLICK, clicked );

..

private function clicked( event:MouseEvent ):void
{
   trace( "Ack I was clicked!" );
}

This would usually be located somewhere within your subclass of one of the InteractiveObject types. To keep with this way of handling interactivity events here is the solution we are going to go with.

We will have a KeyComboDispatcher class. When you create an instance of KeyComboDispatcher you pass it the InteractiveObject instance which owns it. The KeyComboDispatcher class will listen to all events that its owner dispatches. When the KeyComboDispatcher recognizes a combination of keys that have been pressed it will dispatch a KeyComboEvent with information about the combination that was pressed.

You are able to register key combinations for the KeyComboDispatcher to listen for using its addKeyCombo method. The addKeyCombo method allows you to name the combination and set the key codes in their correct order. The KeyComboEvent that is broadcast if the combination is detected contains the name that you gave the combination, and the key codes that make up that combination.

And that’s pretty much how it works, the two classes are well commented so you should be able to learn their inner-workings by following the comments. You can find those classes here

KeyComboDispatcher.as
KeyComboEvent.as

Leave a Reply