On a listener
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
and
stage.addEventListener(KeyboardEvent.KEY_UP, onUp);
you simply listen if ANY key is pressed. In the handlers onDown() and onUp() you need to check witch key was actually pressed. Usually it's done with a switch to keep the code tidy. Here's an example:
private function onDown(e:Event):void
{
switch(e.keyCode)
{
case 65: // this is the keycode for key "a"
keyAPressed = true;
break;
}
}
For movement it's a good idea to make a few variables, like
private var isMoving:Boolean = false;
private var leftPressed:Boolean = false;
private var rightPressed:Boolean = false;
private var goingLeft:Boolean = false;
with this you can have better controls with a loop like this:
private function movementLoop():void
{
if (! isMoving)
return; // if the char's not moving it's safe to return the function
if (goingLeft)
x -= movementSpeed;
else
x += movementSpeed;
}
You can use this site to check the keyCodes for every button: http://www.kirupa.com/developer/as3/using_keyboard_as3.htm
As you can see from this example the movement are handled on a loop that can be called by a timer or ENTER_FRAME event, not from the press of a button. It's important for many reasons, few of them are:
- You're not spamming the movement command by holding the key down.
- Your keyboard handler is smaller and cleaner to read and extend with new implementation
- You can make a NPC move with same methods by modifying the isMoving and direction variables
- Same as above goes to sending this data to server in multiplayer games
- If you press both left and right, the variables can switch direction of the movement, not try to move the player both left and right.
Hope I could answer your question.
Good luck!