AS3控制键盘的方向键代码
package { import flash.display.MovieClip; import flash.events.Event; import flash.events.KeyboardEvent; public class KeyboardController extends MovieClip { private var upArrow:Boolean; private var downArrow:Boolean; private var leftArrow:Boolean; private var rightArrow:Boolean; public function KeyboardController() { /* Wait for object to be added to stage so we can reference it */ this.addEventListener(Event.ADDED_TO_STAGE, init); } private function init(event:Event):void { /* Add keyboard listeners to the stage */ stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed); stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased); /* Run update every frame */ addEventListener(Event.ENTER_FRAME, update); } private function update(event:Event):void { /* Check each arrow and do something if they are pressed */ if(leftArrow) { trace('left Arrow Pressed'); } if(rightArrow) { trace('right Arrow Pressed'); } if(upArrow) { trace('up Arrow Pressed'); } if(downArrow) { trace('down Arrow Pressed'); } } private function handleSpacebar():void { /* Do spacebar action */ trace("Spacebar hit"); } private function keyPressed(event:KeyboardEvent):void { /* Use a switch to determine which key was pressed */ var code:uint = event.keyCode; switch(code) { case 37: leftArrow = true; break; case 38: upArrow = true; break; case 39: rightArrow = true; break; case 40: downArrow = true; break; case 32: handleSpacebar(); break; } } private function keyReleased(event:KeyboardEvent):void { /* Use a switch to determine which key was released */ var code:uint = event.keyCode; switch(code) { case 37: leftArrow = false; break; case 38: upArrow = false; break; case 39: rightArrow = false; break; case 40: downArrow = false; break; } } } }