actionscript-3flashdevelopflash-player-11

Keyboard Event Only Fired From Original Class


Using FlashDevelop, I've got a bit of code to detect keyboard events. The problem is, if I run this code from the main class (Main.as) it'll trigger the event, but not if I go to another class.

For instance, I have the main class, and it has this function

addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
public function onKeyDown(e:KeyboardEvent):void
{
    trace(e.keyCode);
    if (gameState == 1){main.onKeyDown(e);}
}

Now, this works fine in the first class. But when I send it to my second class, MainMenu.as, nothing happens.

        main = new MainMenu();
        addChild(main);
        gameState = 1;

There's no message from either class. If I put the event in the second class, nothing happens. All the other events besides keyboard events still work.


Solution

  • Keyboard events are only forwarded to the MovieClips who has focus (and their parents). If you want to capture all events without any exception, add it to the stage (as it is the parent of everything, it will always receive the event): stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);. Remember to remove the event after you're done with the class (it won't remove itself).

    Another possibility is to force the focus of the stage to your specific class: stage.focus = this;, but I would avoid this if possible.