I recently finished a Flash game under a bone-crushing deadline. I was writing it in AS3 and realized that the good ol’ [COLOR=royalblue]if(Key.isDown())[/COLOR] method was no longer with us.
Upon scouting around I found several approaches using arrays, but they all had serious performance issues; definitely unacceptable to the client.
For anyone pulling his/her hair out with the same problem, here is a routine I cooked up that works:
// target of the code is a MovieClip named "dot"
var left:Boolean = false;
var right:Boolean = false;
var up:Boolean = false;
var down:Boolean = false;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onUp);
addEventListener(Event.ENTER_FRAME, onEnter);
function onDown(e:KeyboardEvent):void{
switch(e.keyCode){
case 37: //left arrow key
left = true;
break;
case 39: //right arrow key
right = true;
break;
case 38: //up arrow key
up = true;
break;
case 40: //down arrow key
down = true;
break;
}
}
function onUp(e:KeyboardEvent):void{
switch(e.keyCode){
case 37: //left
left = false;
break;
case 39: //right
right = false;
break;
case 38: //up
up = false;
break;
case 40: //down
down = false;
break;
}
}
//the following will handle multiple key input for diagonal
//movement, even though there are only four conditions
function onEnter(e:Event):void{
if(left) dot.x -= 2;
if(right) dot.x += 2;
if(up) dot.y -= 2;
if(down) dot.y += 2;
}
A whole lot lengthlier than the same thing in AS2… but when isn’t that the case?