Actionscript Key Listener Tutorial AS3

Overview

Allowing users to use the keyboard as well as the mouse is a great way to incite interaction with your flash. This tutorial will show how to code it and what you can do with some keyboard events. This changed with actionscript 3, note this tutorial is AS3.
altKeY (Boolean) Indicates whether the Alt key is active (true) or inactive (false).
charCode (uint) Contains the character code value of the key pressed or released.
ctrlKey (Boolean) Indicates whether the Control key is active (true) or inactive (false).
keyCode (uint) The key code value of the key pressed or released. KeyboardEvent
keyLocation (uint) Indicates the location of the key on the keyboard. KeyboardEvent
shiftKey (Boolean) Indicates whether the Shift key modifier is active (true) or inactive (false).

Steps

  1. import KeyboardEvent,
    import flash.events.KeyboardEvent;
  2. assign any keycodes
    //keycodes
    var left:uint = 37;
    var up:uint = 38;
    var right:uint = 39;
    var down:uint = 40;
  3. add event listener KeyboardEvent.KEY_DOWN
    stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);
  4. respond to keys
    function keyDownListener(e:KeyboardEvent) {
            trace(e.keyCode.toString());
    }

    or

    function keyDownListener(e:KeyboardEvent) {
            if (e.keyCode==left){
    		ship.x-=10;
    		ship.rotation = 90;
    	}
    	if (e.keyCode==up){
    		ship.y-=10;
    		ship.rotation = 180;
    	}
    	if (e.keyCode==right){
    		ship.x+=10;
    		ship.rotation = 270;
    	}
    	if (e.keyCode==down){
    		ship.y+=10;
    		ship.rotation = 0;
    	}
    }

Example

Here we have a swf with the keyboard event listener on the stage, and feedback boxes to give us all we can know about the event. It will tell us about certain keys (alt, ctrl (cmd), and shift) with a Boolean, it will tell us the keyCode and the charCode. The keyCode is the number that is tied to the actual button pressed or key, and the charCode relates to the character represented by the button(s) pressed. So hitting ‘s’ and then hitting ‘shift + s’ will tell you different charCodes, ‘s’ and ‘S’. but you’ll see that the s key has the same keyCode (you’ll also see the ‘shift’ keyCode as well). If needed you can use the String.fromCharCode function to determine what the charCode for something is. The location on the keyboard is even reported, this helps distinguish between the left shift and the right shift and even the numbers across the qwerty and the numpad on the right of the screen.

Get Adobe Flash player

Actionscript

import flash.events.KeyboardEvent;

//keycodes
var left:uint = 37;
var up:uint = 38;
var right:uint = 39;
var down:uint = 40;

stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener);

function keyDownListener(e:KeyboardEvent) {

feedbackAlt.text = e.altKey.toString();
feedbackCharCode.text = e.charCode.toString();
feedbackChar.text = String.fromCharCode(feedbackCharCode.text);
feedbackCtrl.text = e.ctrlKey.toString();
feedbackKey.text = e.keyCode.toString();
feedbackLoc.text = e.keyLocation.toString();
feedbackShift.text = e.shiftKey.toString();

if (e.keyCode == left){
ship.x-=10;
ship.rotation = 90;
}
if (e.keyCode == up){
ship.y-=10;
ship.rotation = 180;
}
if (e.keyCode == right){
ship.x+=10;
ship.rotation = 270;
}
if (e.keyCode == down){
ship.y+=10;
ship.rotation = 0;
}
}

Download

source file download: key-listener.fla

This entry was posted in tutorial and tagged , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

17 Comments

  1. Twanneman
    Posted August 2, 2008 at 4:45 am | Permalink
  2. Posted August 2, 2008 at 10:59 am | Permalink

    Thanks for pointing that out, Twanneman! My bad… link is fixed now. Enjoy

  3. DJC
    Posted September 1, 2008 at 7:36 pm | Permalink

    Seems the ALT key is intercepted by the OS or app (Flash, browser, etc) in many cases and thus does not generate an event.

  4. Darwin M
    Posted October 29, 2008 at 9:04 am | Permalink

    Hi Evans,

    Great article! It seems like DJC is correct about Mac OS alt(option) key does not respond to the flashplayer. It works with firefox browser, but it does not work in Safari. Is there a way to fix that issue?

    Thanks.

  5. Posted May 1, 2009 at 2:58 pm | Permalink

    Nice post! Thanks for writing this up. Just a little suggestion though… might be more efficient to replace your multiple if() conditional statements with a switch-case statement inside keyDownListener. That way you will perform a minimum number of checks every time the listener is called.

  6. Posted May 2, 2009 at 12:02 pm | Permalink

    True. I guess I just copied pasted the first if statement, should at least be else ifs, but a switch would be the best for the job. Thanks!

  7. WORMSS
    Posted August 27, 2009 at 2:35 am | Permalink

    I was just wondering why you are storing left, right, up & down and not using Keyboard.LEFT, Keyboard.RIGHT, Keyboard.UP & Keyboard.DOWN?

  8. Nguyen Ho Thanh
    Posted January 12, 2010 at 3:58 pm | Permalink

    I don’t understand that at all. I did exactly like what you’ve shown and it reports error like “1120: Acceess of undefined property “.

    what should I put into the property of the movie clip.

  9. Kirill Panshin
    Posted January 24, 2011 at 9:52 am | Permalink

    In the demo on this webpage I have ‘Alt’ key ‘False’ with all keys except Alt + Ctrl

  10. Gus
    Posted May 1, 2011 at 9:27 am | Permalink

    Notice how when you hold an arrow the ship moves once, then there is a pause, then it begins moving quickly again… How do I remove the pause for smoothness?

    Number two, How do you register two keypresses at once???

    Any help would be excellent

    • Posted May 3, 2011 at 11:44 am | Permalink

      Hey Gus,
      Check out this discussion, the pause isn’t the “fault” of flash, but the OS. I’m guessing it was by design so if you’re typing and are slow to lift your finger on a key, you don’t end up having the character repeaaaated. There is a suggestion listed that may help that looks ok, but I haven’t tried it: http://board.flashkit.com/board/showthread.php?threadid=815876
      Regarding having multiple keys pressed simultaneously, it seems to me that they work, but when it doesn’t (and I suspect this is what you’re after) is when you hold two keys down and are expecting them to both continue firing. Like moving left and up together to go diagonally. The above link may still help and it seems the reasoning is the same per the OS controlling the actual keyboard events of the UI apparatus.

      • Gus
        Posted May 9, 2011 at 6:28 am | Permalink

        Thanks anyway, but I found an AS3 package that re-creates the old AS2 Key.isDown functionality, but with AS3. Its at
        If anyone is looking for it, (and my god its useful), find it here

        com.senocular.utils.KeyObject.as

  11. Posted May 3, 2011 at 1:00 pm | Permalink

    Your online version works perfectly. It gives different keycodes for the number pad versus the same character on the main keyboard. However, when I use the code and build my own .fla and then publish it, it the keycodes for the same character are identical on both the keypad and the main keyboard. How can I make the code work correctly like your online version does?

    • Posted May 3, 2011 at 11:53 am | Permalink

      Are you sure you’re looking at the charCode vs the keyCode? If you hit the ’1′ key in the keyboard and the ’1′ key on the number pad you should get the same charCode but a different keyCode.

  12. Posted June 17, 2011 at 10:54 am | Permalink

    This is exactly what I’ve been looking for! Thank you…someone finally wrote it in a way that makes sense to me.

  13. Trent
    Posted August 16, 2011 at 12:07 am | Permalink

    Nice to see a simple tutorial that actually works.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Recent Posts

    Developing for old browsers is (almost) a thing of the past – (37signals)

    Basecamp announces that it’s new version will not support old browsers! They will of course continue to support them in their “classic” version. But this is good news and as more implement this type of policy the internet will be happy. It used to be one of the biggest pains of web development. Juggling different [...]

    Screen shot 2012-02-10 at 12.59.33 PM

    Vendor Prefixes – about to go south

    What are “standards” coming to? Who’s guilty? Apple and Chrome: They’re supporting vendor prefixed properties like they’re a standard part of development. Firefox, Opera and Internet Explorer: They should have been on the ball more. Need to push their evangelism further. Teach developers that it’s not exclusively -webkit to style elements. All the browsers: experimental [...]

    bio

    An Event Apart Notes: Ethan Marcotte, Responsive Web Design

    Ethan Marcotte has become the father of Responsive Web Design and spent this whole day focused on principles, techniques, gotchas, examples, … all about building and how to build responsive sites. With a sprinkle of mobile first. For Ethan, it all started with this article: http://www.alistapart.com/articles/dao/ Think of architecture, the whole design phase is established [...]

    Webcomm_Montreal

    An Event Apart Notes: Jared Spool, The Curious Properties of Intuitive Web Pages

    Senseless waste of asterisks… Avis used an asterisk to denote optional fields. This means that there is a lot of baggage that comes with an asterixk. Somewhere this symbol got meaning, it’s not in the bible! We can control when something goes from unintuitive to intuitive. A design is intuitive (although technically and grammatically speaking [...]

    untitled-158-2

    An Event Apart Notes: Marco Arment, Bridging the App Gap

    The iPhone changed our industry in 2007: first mobile to have a desktop class web browser and it made people start using their mobile phones as computers! All apps other than apple provided ones were web browser apps. Most of the first apps were branded web browsers. No real difference between using mobile site or [...]

    lukew_space

    An Event Apart Notes: Luke Wroblewski, Mobile to the Future

    MASS MEDIA (in waves) Print, Recordings, Cinema, Radio, Television, Internet, Mobile Mobile is the new Mass Media It certainly is mass and massive. More mobile devices (by far) every day than babies born on the planet. Mobile devices are eating into our personal computing shares. New waves of mobile media eat all previous media waves. [...]

    IMG_4500

    An Event Apart Notes: Josh Clark, Buttons are a Hack

    Mobile and touch should be revolutionizing design and user experience. We don’t want to touch a tiny link or button. Back button is just stupid. Fitz’s Law, make things fat proximal targets for easy touching. People are lazy, let’s as designers LET people be lazy! Maybe even use the whole screen as your control. Eliminate [...]

    nicole_pink_bkg_2012

    An Event Apart Notes: Nicole Sullivan, Our Best Practices are Killing Us

    Grep to for analyze css. CSS duplication is a web-wide problem. Started helping facebook optimize thier site and they had 1.9MB of css loading. The same color showing up hundreds of times. Many many color statements and declarations. !important declarations get dangerous. Sites found to have over 500 !important declarations! float is a serious problem [...]

    ericmeyer

    An Event Apart Notes: Eric Meyer, The Future of CSS

    Cormorant trained to fish for the fishermen. The fishermen tie bands around the birds necks that are. Fishermen fish at night, using lamps they attract bugs, which attract fish, and the cormorant get to fish but cant swallow them and the fishermen take the fish. Browser vendors are promising us new CSS tools, but don’t [...]

    sammyj

    An Event Apart Notes: Ethan Marcotte, Rolling Up Our Responsive Sleeves

    Henry Adams (Descendant of 2 presidents: great-grandson to John Adams and grandson to John Quincy Adams). He lived between the civil war and world war 1. He witnessed the industrial revolution. Chaos was the law of nature, Order was the dream of man Samuel Johnson – funniest man in the 17th Century… Responsive Design: 1. [...]

  • Recent Comments

    me-gamer

    me-gamer

    this is really nice. this made many of my task simple.
    Lori Newman

    Lori Newman

    Just wanted to thank you for your presentation. It was extremely informative and just what I...
    Karl

    Karl

    I have been using for some time this nice Banner, from developer FX. They have a really nice Live...
    Karl

    Karl

    Thank you for this wonderful link… recommend it! Fast, simple, easy… :-)
    Gabriel

    Gabriel

    Hi Valerie, I don’t know if you are still following this post, but I tried seeing if it is...
    avinash

    avinash

    Hi Evan, I am using the same code and trying it on chrome/firefox it is not working on neither...