Multiple keys made easy with Dictionary
Quick 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.
private var currentKeys:Dictionary = new Dictionary();
Then, in your constructor or wherever you assign eventListeners, add these (well-known) listeners, with the callback functions:
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;
}
Inside your enterframe-event or timer (were you want to detect which keys are pressed), you could these kind of detection.
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;
}
}
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.
Nice one, was looking for exactly this! You just save me a bunch of time 🙂
Cheers, Sid
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.
Thanks Jackson, you are absolutely right.
I knew this thing for long time.
Thanks for the tip anyway. Its the best way to control keys.
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;
}
@thomas; smart one 🙂