ritual_code
ritual_code

Reputation: 147

AS3 Keyboard events

How would one go about adding event listeners for multiple keystrokes, for example if the up and right buttons are pressed player goes diagonally in that direction.

Upvotes: 0

Views: 4251

Answers (1)

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

Check out the following code, I store the pressed key in a object and then animated a sprite using the object :

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--;
            }
        }

    }

}

Upvotes: 3

Related Questions