Multiple keys made easy with Dictionary (6)

, under actionscript, Code snippets.

Multiple keys made easy with DictionaryQuick post here, a simple solution I found to have multiple keys enabled. Maybe most real game developers know better or more elegant solutions, but I found this useful enough to share it with you.

Here we go. Add these variable to your class. This is a Dictionary, which allows you to associate a value with an object key.
[as]
private var currentKeys:Dictionary = new Dictionary();
[/as]
Then, in your constructor or wherever you assign eventListeners, add these (well-known) listeners, with the callback functions:
[as]
import flash.events.KeyboardEvent;

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);

private function onKeyDown(e:KeyboardEvent):void
{
currentKeys[e.keyCode] = true;
}

private function onKeyUp(e:KeyboardEvent):void
{
currentKeys[e.keyCode] = false;
}
[/as]
Inside your enterframe-event or timer (were you want to detect which keys are pressed), you could these kind of detection.
[as]
import flash.ui.Keyboard;
import flash.events.Event;

private function onUpdate(e:Event):void
{
if ( currentKeys[ Keyboard.SPACE ] )
{
tank.shoot();
}
if ( currentKeys[ Keyboard.RIGHT ] )
{
tank.targetDirection -= 0.1;
}
if ( currentKeys[ Keyboard.LEFT ] )
{
tank.targetDirection += 0.1;
}
if ( currentKeys[ Keyboard.UP ] )
{
tank.speed += tank.acceleration;
}
if ( currentKeys[ Keyboard.DOWN ] )
{
tank.speed /= 1.8;
}
}
[/as]
I found that if you use some 3 or 4+ combinations of keys at the same time, the keyboard events are not triggered anymore, which is a bit of annoying bug in the FlashPlayer. I mean pressing forward and left and shooting at the same time could be a problem? Well; Hope this helps, I think its very easy and a great usage of the Dictionary.

6 responses to “Multiple keys made easy with Dictionary”

  1. Nice one, was looking for exactly this! You just save me a bunch of time 🙂

    Cheers, Sid

  2. This is a good way to program for the keyboard by polling rather than by events. Just be sure to keep in mind that a lot of keyboards won’t do more than a couple of keys though.

  3. Mark says:

    Thanks Jackson, you are absolutely right.

  4. AlexG says:

    I knew this thing for long time.
    Thanks for the tip anyway. Its the best way to control keys.

  5. Thomas says:

    i ususally use an other, shorter notation:

    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyStateHandler);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyStateHandler);

    private function keyStateHandler(e:KeyboardEvent):void
    {
    currentKeys[e.keyCode] = e.type == KeyboardEvent.KEY_DOWN;
    }

  6. Mark says:

    @thomas; smart one 🙂

Say something interesting

Please link to code from an external resource, like gist.github.com.