AS3 Key.isDown() behavior

Some game developers may have noticed that the Key.isDown() method is absent in AS3… which is a rather unhandy omission for developers trying to build a game with keyboard controls for avatar movement. Rather than just knowing when a key is pressed, you need to be able to check to see if the key is STILL pressed each frame. I’m not sure if Adobe deemed the Key.isDown() method as bad form or if they just figured that the average developer is smart enough to manufacture a replacement solution for it. Either way, here’s a AS3 replacement for those who miss it. You can call this test as: “isKeyPressed(keyCode);”

import flash.events.KeyboardEvent;
import flash.ui.Keyboard;

var _keys:Array = new Array();
stage.addEventListener(KeyboardEvent.KEY_DOWN, this.handleKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, this.handleKeyUp);

function handleKeyDown(evt:KeyboardEvent):void
{
    if (_keys.indexOf(evt.keyCode) == -1)
    {
        _keys.push(evt.keyCode);
    }
}

function handleKeyUp(evt:KeyboardEvent):void
{
    var i:int = _keys.indexOf(evt.keyCode);

    if (i > -1)
    {
        _keys.splice(i, 1);
    }
}

function isKeyPressed(key:int):Boolean
{
    return _keys.indexOf(key) > -1;
}
Advertisements

2 comments so far

  1. Tarwin Stroh-Spijer on

    Yeah, this was a real bastard when I first started with AS3. I’ve developed a pretty good class that handles it for me though and you’ve inspired me to fix it up and do a blog post about it – so you can get it at http://blog.touchmypixel.com/archives/24

    I think the way you’ve done it above is pretty slow – calling array.indexOf and array.splice is pretty intensive. The way I’ve done it is to just keep a Boolean for each key in an array. Seeing as your only ever going to have less than 256 keys down (I think keyboards can only ever send through 256 key codes, I could be wrong?!) then you just need an array with 256 values, and you can do a simple array index check to see if a key is pressed, so the above becomes:

    function function isKeyPressed(key:int):Boolean
    {
    return keys[int];
    }

    • bigmac on

      Yep – that’s a very good point. 256 values in an array would be lighter, especially with nothing but Booleans.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: