# Reliable AS3 multiple keypress

**URL:** <https://forum.kirupa.com/t/reliable-as3-multiple-keypress/310916>\
**Category:** flash\
**Created:** [June 22, 2010, 8:56pm UTC](https://forum.kirupa.com/t/reliable-as3-multiple-keypress/310916 "2010-06-22T20:56:36Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![bhnh](https://avatars.discourse-cdn.com/v4/letter/b/eb8c5e/32.png) [@bhnh](https://forum.kirupa.com/u/bhnh)\
**Post date:** [June 22, 2010, 8:56pm UTC](https://forum.kirupa.com/t/reliable-as3-multiple-keypress/310916/1 "2010-06-22T20:56:36Z")

</div>

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_:

```auto

 
// 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? 😏
