Below is the keyboard class i use when building any flash projects which require keyboard controls.
Over my years as an as3 developer I have seen many different implementations of the simple character movement code.
I often see people attaching the character movement script directly to the event handlers; that is not a good idea, as it causes a movement stutter when the user initially presses and holds down a movement key.
Instead its recommended (by me) to set boolean flagging when a direction has been invoked, and manage those states with an enter frame event.
Below is the simple script I use for the basis of top down character movement. You could then add player rotations, acceleration, or an OOP approach for managing the script. Either way make sure you manage your player movement on the game loop and not directly keyboard event handlers
package { import flash.events.Event; import flash.events.KeyboardEvent; /* Author John Stejskal */ public class Game extends Sprite { private var isRight:Boolean = false; private var isLeft:Boolean = false; private var isUp:Boolean = false; private var isDown:Boolean = false; private var _moveSpeed:int = 5; private var _mcPlayer:Player; public function Game() { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); //create player and place in center of stage _mcPlayer:Player = new Player(); _mcPlayer.x = stage.stageWidth/2; _mcPlayer.y = stage.stageHeight/2; stage.addChild(_mcPlayer) //Add keyboard listeners stage.addEventListener(KeyboardEvent.KEY_DOWN, downKey); stage.addEventListener(KeyboardEvent.KEY_UP, upKey); //add game loop stage.addEventListener(Event.ENTER_FRAME, loop); } //------------------------------o // Keyboard Event Handlers //------------------------------o private function downKey(event:KeyboardEvent) { //right press if(event.keyCode==39){ isRight = true} //left pressed if(event.keyCode==37){ isLeft = true} //up pressed if(event.keyCode==38){ isUp = true } //down pressed if(event.keyCode==40){ isDown = true } } private function upKey(event:KeyboardEvent) { //right released if(event.keyCode==39){ isRight = false} //left released if(event.keyCode==37){ isLeft = false} //up released if(event.keyCode==38){ isUp = false } //down released if(event.keyCode==40){ isDown = false } } //----------------------------------------o // Check if keys are down and move player //----------------------------------------o private function loop(Event) { if(isRight){_mcPlayer.x+=_moveSpeed} if(isLeft){_mcPlayer.x-=_moveSpeed} if(isUp){_mcPlayer.y-=_moveSpeed} if (isDown) {_mcPlayer.y += _moveSpeed} } } }
You can find keyboard const in
flash.ui.Keyboard
so you can write Keyboard.UP instead of 39 etc.
Keep working ,impressive job!