AS3: KeyboardEvents, KeyCodes, and CharCodes

Once you really get going into designing basically any kind of computer game – whether it be a 2-D platformer like Contra or even online video Poker – you are eventually going to need some kind of keyboard control besides general typing. Traditionally this could be the arrow keys or W,A,S,D for movement, spacebar for jumping or plasma-ray firing, R for retry or Q for quit, but really the level of control is up to you.

A keyCode is an integer representing a particular type of key on your keyboard. By differentiating between one keyCode and another in Flash, we can trigger separate events based on each individual keyboard key or combination of.

The example above displays the keyCode for each keyboard button.

Note: You will have to click the example to give your keyboard’s focus to the flash player.

Actionscript:

1
import flash.events.KeyboardEvent;

All you need to import is the KeyboardEvent class for our example.

Actionscript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyEvent);

function onKeyEvent(e:KeyboardEvent):void
{
    var character:String = String.fromCharCode(e.charCode);

    if (e.keyCode == 66)
    {
        trace(character);   //'b' or 'B'
    }
    else if (e.keyCode == 83 && e.shiftKey)
    {
        trace(character);   //'S' only
    }
}
What we do here is:
  1. Attach a KeyboardEvent listener to the stage
  2. Create a new String of the pressed keyboard character
  3. Listen for a particular key press that triggers an action

Actionscript:

1
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyEvent);

Here we create a new event listener and attach it to the stage. We define the listener to be of type KeyboardEvent and to listen for any KEY_UP events. Lastly we instruct the listener to call function onKeyEvent every time this event occurs. Roughly speaking, every time we release a keyboard key we do something.

Actionscript:

1
var character:String = String.fromCharCode(e.charCode);

Once we are working within our event fired function, onKeyEvent, we have access to all of the information concerning that event through ‘e‘. We can extract a lot from the event for just a simple button press, but for now we will just look at a particularly handy bit of info – charCode.

CharCode

charCode is an ASCII code that represents a character on a keyboard. (a,b,c,D,E,F,1,2,3,!,@,#..) Each character has its own unique code – For instance: the charCode for ‘A’ is 65, being different from ‘a’ which is 97. Even a spacebar space has a charCode (32) because each space is a recognized character.

Note: Keyboard buttons like ‘Enter’, ‘Ctrl’, and ‘Num Lock’ do not have charCodes. (They return a charCode of 0)

In the code snippet above we do something relatively complex to accomplish a task assumedly simple. We convert the typed keyboard character’s ASCII alter-ego into the character we understand intelligibly. Your OS does this constantly for you when in fact all your keyboard knows is which key is pressed. This is necessary for keyboards of multiple languages to function.

fromCharCode(... charCodes):String

So, what we accomplish here is: fromCharCode – a method of the String class – takes a charCode, converts it and returns the respective character as a String which we then pass to a new variable character.

Actionscript:

1
2
3
4
if (e.keyCode == 66)
{
    trace(character);   //'b' or 'B'
}
KeyCode

Now that we understand charCode, keyCode should be easy. Like briefly mentioned above, a keyCode is a number associated with a button on your keyboard – contrary to a character like that of a charCode. Working with a keyCode for keyboard driven events is more useful than charCodes because generally: for instance, when ‘X’ is pressed you are not concerned with whether or not it is the capitalized form or not.

In the above ‘if statement’, we simply evaluate whether the keyCode input is equal to 66 (The code for the ‘B’ key). If this is true we print character,which we captured in the previous block, to the output screen. Since 66 in this case pertains only to the keyboard button for ‘B’, character could be either lowercase ‘b’ or capital ‘B’.

You could replace this trace with anything! In the example at the top, character is placed inside of a text box and randomly attached to the stage.

Actionscript:

1
2
3
4
else if (e.keyCode == 83 && e.shiftKey)
{
    trace(character);   //'S' only
}

Here our code is a lot like the last block except this time, in addition to needing a particular keyCode, we are listening for the Shift key. The shiftKey Boolean is yet another KeyboardEvent attribute we have access to that tells us whether or not the Shift key is pressed. Ergo, if we press both the ‘S’ key (83) and the Shift key we will satisfy the statement and trace character. In this case, since the Shift key is down, we can only expect a capital ‘S’ (Granted Caps Lock isn’t on :)).

Besides Shift, KeyboardEvent also lets us listen for Ctrl and Alt. Check out the Adobe documentation for all of the attributes.

Concluding..

By now you should hopefully have a better understanding of the KeyboardEvent class. Feel free to post or message me with any additional questions you might have!

The source to the example is available below

Note: When testing the example inside the Flash IDE, the internal shortcut keys tend to override your programmed events. To prevent this you will need to disable them. Control > Disable Keyboard Shortcuts

Ben

15 thoughts on “AS3: KeyboardEvents, KeyCodes, and CharCodes

  1. vern

    thanks for the tip re: the shorcuts within the Flash IDE… I was pulling my hair out regarding that issue until I read you “concluding..” note.

  2. deisgnerGirl

    thank you for the explanation: it was very helpful. Adobe docs are not very helpful on this topic. I do wonder why would Flash show as code hint that all characters of the keyboard can be used as a constant, as in Keyboard.t for example when you can’t really use them directly. Am I missing something? It works great with keyboard.UP, for example, but not for regular letters.

  3. Ben Post author

    You can use the Keyboard class for regular letters using AIR, but standard AS3 just gives you the special keys. You could always extend flash.ui.Keyboard and add letters.

  4. Pingback: ฝึกงานวัน ที่สิบเจ็ด-ยี่สิบสาม ณ GMM ฝ่าย Multimedia

  5. Jamie

    I’m an AS3 newbie, but to get your code to work I had to change anywhere you had an ‘e’ to the full word ‘event’. Maybe you pros know something I don’t but I couldn’t get it to work any other way.

    Also it might be helpful to your readers to know they can use an ‘or’ statement for if the user accidentally has caps lock on, so if they hit the Capital letter the same thing happens for the lower case letter- “if ((event.keyCode == 102) || (event.keyCode == 70))” -if ‘f’ or if ‘F’

  6. Reid Quesnell

    alright so I spent the last 15 minutes looking for the same template you’re using and cannot find it. Didn’t want to have to ask but really would love to use it for my site, could you let me know? I’ll look back here soon for any replies. Thanks

  7. Pingback: AS3: KeyboardEvents, KeyCodes, and CharCodes | Ben Silvis « Geek Devigner

  8. Tommy Layell

    I wish more people would write sites like this that are actually helpful to read. With all the fluff floating around on the net, it is a great change of pace to read a site like yours instead.

  9. Pingback: Class Notes ActionScript 3.0 for Flash CS5 June 2010 Washington, DC | My Blog

  10. Gaian Helmers

    Hey, I thought I should let you know that this page is a godsend. It’s been a constant tool for my game development, I have this page always up on my computer so when I need to add any new keys to my key events function I just pop onto your page and use your example, works every time.

    Excellent page and an excellent utility.

  11. Ben Post author

    Thank you very much Gaian. I do the exact same thing. Some things are just easier to look up than memorize.

  12. 이원진

    hi. i’m a student
    i searched on google for 3 hours.
    and finally, i find this blog.
    this script is very kind and good.

    i want to tell you appreciate
    thank you.

    i am sorry not to be good at english. (i can’t total appreciate about your help)

Leave a Reply

Your email address will not be published. Required fields are marked *