Radicate
Radicate

Reputation: 3034

AS3 Key Down event listener doesn't work?

I'm new to OOP programming with AS3, I'm trying to create a listener that will respond when keys are pressed..

It worked fine when I just typed it in the timeline, but now when it's on it's own package it doesn't respond at all, what am I doing wrong?

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

    public class PlayerController extends Sprite{
        public function PlayerController(){
            addEventListener(KeyboardEvent.KEY_DOWN,onButDown);
        }
        function onButDown(event:KeyboardEvent):void{
            trace("Key Down");
        }
    }

}

And in the main class I have this:

var pc:PlayerController = new PlayerController();

Thanks

Upvotes: 0

Views: 2558

Answers (2)

Marcela
Marcela

Reputation: 3728

Your issue here may be that the instance of PlayerController has not received focus (and never will since it doesn't look like you're adding it to the display list). If an object does not have focus, it cannot receive keyboard events.

One solution would be to pass a reference to stage in your constructor and then add the event listener to that instead:

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

    public class PlayerController extends Sprite{
        public function PlayerController($stageRef:Stage){
            $stageRef.addEventListener(KeyboardEvent.KEY_DOWN,onButDown);
        }
        function onButDown(event:KeyboardEvent):void{
            trace("Key Down");
        }
    }

}

Then, in your main app:

var pc:PlayerController = new PlayerController(stage);

Edit to add: this is assuming stage is not null. You would need to make sure of that before you instantiate PlayerController in this manner.

Upvotes: 1

David
David

Reputation: 887

Generally, you're supposed to put all event listeners and the functions they call for in the main class. That is all.

Upvotes: 0

Related Questions