ActionScript 3 KeyboardEvent not firing

家住魔仙堡 提交于 2019-12-08 07:08:49

问题


I'm new to ActionScript development and am using the FlashDevelop IDE. I've been playing around with some really simplistic things and have come across a problem I can't seem to solve.

My application compiles and runs, and a function that watches click events fires perfectly and I can see the event in the console when I pass it to trace(), yet the same code watching for KeyboardEvent fails to fire at all.

Here's my code:

package GameTesting
{

    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Sprite;

    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.events.KeyboardEvent;

    [Frame(factoryClass="GameTesting.Preloader")]
    public class Main extends 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);

            addEventListener(MouseEvent.CLICK, onClickEvent);
            addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownEvent);
        }

        private function onKeyDownEvent(e:KeyboardEvent):void
        {
            trace(e);
        }

        private function onClickEvent(e:MouseEvent):void
        {
            trace(e);
        }

    }

}

The MouseEvent trace() fires every time as expected, but KeyboardEvent never fires, no matter what key I press. Any ideas?


回答1:


You need to add the listeners to the stage:

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

    stage.addEventListener(MouseEvent.CLICK, onClickEvent);
    stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDownEvent);
}



回答2:


You may need to be sure the movieclip listening for the event has focus. If you have some sort of menu or start screen for your game that you click a button on to start, that movieclip can retain focus even if it has been removed from stage.

Here's a good article explaining this in further detail: Keyboard events on stage are not working...?




回答3:


If you are in the Flash IDE (for CS4 at least) you will also need to disable the keyboard shortcuts when you debug (Ctrl+Shift+Enter) or test (Ctrl+Enter) the fla.

In the movie window, select 'Control'->'Disable Keyboard Shortcuts'. This will stop the Flash IDE recieving the keyboard input, and allow the debug/test window to instead.



来源:https://stackoverflow.com/questions/4100402/actionscript-3-keyboardevent-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!