Ben Silvis

Game Development in Flash

AS3: Intro to Using Sprite Sheets »« AS3: Applying a BlurFilter Effect

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
Download Source
Share and Enjoy:
  • Google Bookmarks
  • Digg
  • Facebook
  • LinkedIn
  • Twitter
  • del.icio.us
  • StumbleUpon
  • Technorati
, , ,
October 8, 2009 at 7:54 pm
6 comments »
  • February 18, 2010 at 6:38 amvern

    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.

  • February 18, 2010 at 10:31 amBen

    Glad it was useful!

  • April 22, 2010 at 12:04 amdeisgnerGirl

    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.

  • April 22, 2010 at 11:25 amBen

    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.

  • August 25, 2010 at 2:03 pmJamie

    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’


Trackbacks/Pingbacks
Leave a Reply or trackback