SentineL
SentineL

Reputation: 4732

ActionScript 3 Event doesn't work

I'm new in AS, and trying to make my first application. I have a class, that showld manage some events, like keyboard key pressing:

public class GameObjectController extends Sprite
{
    var textField:TextField;

    public function GameObjectController()
    {
        addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
    }

    private function onKeyDown(event: KeyboardEvent):void
    {
        trace("123");
    }
}

but when I'm running it, and pressing any button, nothing happands. What am I doing wrong?

Upvotes: 1

Views: 398

Answers (2)

Chunky Chunk
Chunky Chunk

Reputation: 17217

Add the keyboard event to the stage and import the KeyboardEvent class.

package
{
    import flash.display.Sprite;
    import flash.events.KeyboardEvent;

    public class GameObjectController extends Sprite
    {
        public function GameObjectController()
        {
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownEventHandler);
        }

        private function keyDownEventHandler(event:KeyboardEvent):void
        {
            trace(event);
        }
    }
}

Upvotes: 0

Marty
Marty

Reputation: 39456

Try stage.addEventListener() for KeyboardEvents.

The reason for this is that whatever you add the event to needs focus, and the stage always has focus.

If GameObjectController isn't the document class, it will need to have stage parsed to its constructor for this to work, or it will need to be added to the stage first. The former will be less messy to implement.

public function GameObjectController(stage:Stage)
{
    stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}

Upvotes: 3

Related Questions