AS3键盘事件

时间:2013-04-14 01:04:31

标签: actionscript-3 keyboard-events event-listener

如何为多次击键添加事件监听器,例如,如果按下向上和向右按钮,则玩家沿着该方向倾斜。

1 个答案:

答案 0 :(得分:3)

检查下面的代码,我将按下的键存储在一个对象中,然后使用该对象激活一个精灵:

package 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;

    public class Main extends Sprite 
    {
        private var _keys:Object = { };
        private var _sprite:Sprite = new Sprite;

        public function Main():void 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            // entry point

            _sprite.graphics.beginFill(0xff0000, 1);
            _sprite.graphics.drawRect(0, 0, 40, 40);
            _sprite.graphics.endFill();
            _sprite.x = 100;
            _sprite.y = 100;
            addChild(_sprite);

            stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
            stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
            stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }

        private function onKeyDown(e:KeyboardEvent):void 
        {
            _keys[e.keyCode] = true;
        }

        private function onKeyUp(e:KeyboardEvent):void 
        {
            _keys[e.keyCode] = false;   
        }

        private function onEnterFrame(e:Event):void 
        {

            if (_keys[Keyboard.UP])
            {
                _sprite.y --;
            }

            if (_keys[Keyboard.DOWN])
            {
                _sprite.y ++;
            }

            if (_keys[Keyboard.RIGHT])
            {
                _sprite.x++;
            }

            if (_keys[Keyboard.LEFT])
            {
                _sprite.x--;
            }
        }

    }

}