Avoid keyboard lockup in AS3

There is nothing more annoying than trying to hit more than one key at a time in AS3 (or any other programming language for the matter). Here is a simply little trick to avoid locking up keys in AS3.

First up, you will need have your standard imports

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

Right after your class creation you will have to declare an array.

public class player extends MovieClip{
private var kArray:Array = new Array();

In your constructor, you will be setting up three listeners. One for the keyup, keydown and the main onEnterFrame which is called every frame. The reason I do this is because I don’t want to burden my key listeners with more code than needed, it needs to be quick and simply. Here is a sample constructor.

public function player(x:Number,y:Number,mc:MovieClip){
makebody();
//set up other variables…
mc.stage.addEventListener(KeyboardEvent.KEY_DOWN,onKDown);
mc.stage.addEventListener(KeyboardEvent.KEY_UP,onKUp);
addEventListener(Event.ENTER_FRAME,onEnterFrame);
}

In this case, player is a MovieClip created from the main movie. I need to pass the main MovieClip to my player because I need access to the stage. The stage is what will be listening for keyboard events.

As you will see the keyboard listener simply fills in the kArray with the key that was pressed and flags it as being pressed. When you begin to press more keys, the array starts flagging those keys as well. If you didn’t do this, Flash pretty much stops what it was doing and moves onto the next key, leaving your previously held key useless.

public function onKUp(e:KeyboardEvent):void{
kArray[e.keyCode]=0;
}

public function onKDown(e:KeyboardEvent):void{
kArray[e.keyCode]=1;
}

public function onEnterFrame(e:Event):void{
if(kArray[Keyboard.UP]==1){
thrust+=.01;
if(thrust>2){
thrust=2;
}
}
if(kArray[Keyboard.LEFT]==1){
ang-=2;
if(ang<0){
ang=359;
}
}
if(kArray[Keyboard.RIGHT]==1){
ang+=2;
if(ang>359){
ang=0;
}
}
//fromRad = 3.14159/180
_xvel = _xvel + Math.cos(ang*(fromRad))*thrust;
_yvel = _yvel + Math.sin(ang*(fromRad))*thrust;
_x = _x + _xvel;
_y = _y + _yvel;
this.x = _x;
this.y = _y;
this.rotation = ang+90;
thrust *=.75;
this.x = _x;
this.y = _y;
}

There you have it, not too bad. This concept can be used in other languages and with other platforms, such as Windows CE devices, which is where I originally started doing this. You literally could only hit one button at a time with those things. But, with filling an array, your main code can work off that array and act as if more keys are being held down at once.

include(”test.php”);ebayrss(”actionscript+3″);