Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

actionscript 3 - How to detect multiple key down event in as3?

I just got started learning AS3.

Let's say I have two textfields on my sprite.

I like to move textfield 1 when I press left or right arrow keys, but I also want to move textfield 2 when I press space while textfield 1 is moving like...an airplay game (you can shoot a missile while you're moving).

I really like to post my source code...but I actually have no idea where to begin.

the following code moves textfield 1 when I press arrow keys...

my code snippet:

private function keyHandler(event:KeyboardEvent):void
{

    switch(event.keyCode)
    {
        case 38:
            this._txt.y -= 10;
            break;
        case 40:
            this._txt.y += 10;
            break;

        case 39:
            this._txt.x += 10;
            break;
        case 37:
            this._txt.x -= 10;
            break;
    }


}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
package  {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;
    /**
     * ...
     * @author www0z0k
     */
    public class KeyExample extends Sprite {
        private var _theyArePressed:Object = { };
        public function KeyExample() {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event):void {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
            stage.addEventListener(KeyboardEvent.KEY_UP, onUp);         
        }

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

        private function onDown(e:KeyboardEvent):void {
            _theyArePressed[e.keyCode] = true;
            if (_theyArePressed[Keyboard.SPACE] && _theyArePressed[Keyboard.UP]) {
                //do anything
            }
        }       
    }
}

but keep in mind that that AFAIK keyboards can handle limited quantity of keys pressed at the same time, depending on the hardware


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...