Tracking key presses can be useful both form Flash games (i.e. up, down, left, right keys) or even forms and other types of interactivity (enter key, etc.). It’s pretty simple to do in AS3 using the KeyboardEvent object. Here are a couple examples:
The first thing we need to do is set up a listener to track key events:
//Listen for key presses
stage.addEventListener(KeyboardEvent.KEY_DOWN, key_pressed);
So basically we are saying when someone presses down a key we want to run the “key_pressed” function. Let’s create that function now.
There are a couple different ways to track which key is pressed. For the widest range of keys we’ll use the charCode. This is an integer that represents each key on the keyboard. Here’s an example to do that:
//Listen for key presses
stage.addEventListener(KeyboardEvent.KEY_DOWN, key_pressed);
//trace a particular key press
function key_pressed(event:KeyboardEvent):void {
//trace(event.charCode);
if (event.charCode == 65) {
trace(”A”)
}
if (event.charCode == 97) {
trace(”a”)
}
}
There is a list of charCodes here.
You’ll notice that the link above only has charCodes for upper case letters. One way to figure out charCodes for a lower case (or any) key is to trace the charCode as you press a key. Uncomment the trace(event.charCode); line in the code above and Flash will trace a charCode each time you press a key.
Now for some keys there is an even easier way to track pressing. It’s called keyCode and it is more readable than the cryptic charCode. Here is some sample code for that:
//Listen for key presses
stage.addEventListener(KeyboardEvent.KEY_DOWN, key_pressed);
//trace a particular key press
function key_pressed(event:KeyboardEvent):void {
switch (event.keyCode) {
case Keyboard.SPACE:
trace(”space”)
break;
case Keyboard.UP:
trace(”up”)
break;
case Keyboard.NUMPAD_4:
trace(”4″)
break;
case Keyboard.INSERT:
trace(”Insert”)
break;
/*for this trace to work while testing your movie you’ll need to go to
Control>>Disable Keyboard Shortcuts in the window’s menu*/
case Keyboard.F1:
trace(”F1″)
break;
}
}
You can get the keyCodes for that method at the same link as above.
Note - if you see the little AIR logo before the keyCode, it means that particular keyCode only works in the AIR runtime. Or should I say Adobe AIR Runtime… which translates to Adobe Adobe Integrated Runtime Runtime. Sorry … tangent.
So for any keyCodes with that logo in front, you’ll need to use the charCode method I outlined above.
Friends - I hope this helps you accomplish all of your wildest key press tracking dreams! Good luck!