apscience
apscience

Reputation: 7253

Key press not triggering KeyboardEvent

I'm starting a simple pong game, and I created a Paddle class that doesn't do anything yet. However, I don't think it is working.

package  
{
    import flash.display.MovieClip;
    import flash.events.KeyboardEvent;
    public class Paddle extends MovieClip
    {
            private var paddleSpeed:int = 4;

            public function Paddle() 
            {
                trace("hello!")
                addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
            }

            public function keyDown(e:KeyboardEvent):void
            {
                trace(e.keyCode);
            }

    }

}

In Main.as I have done this:

var player:Paddle = new Paddle;
addChild(player);

When I run the code, I get hello!, but when I press any key nothing happens. I've read a KeyboardEvent tutorial, and I'm doing what they are doing. Thanks for any help

Upvotes: 1

Views: 1706

Answers (2)

Marty
Marty

Reputation: 39456

Try adding the event listener to stage instead of Paddle. Also, when you're testing your project make sure you have keyboard shortcuts disabled.

enter image description here

What I actually normally do is make a Keyboard class with a down() function that I can reference throughout the application. Its use would be something like this:

if(Keyboard.down(65, 67))
{
    trace("A and/or C are being held down!");
}

Upvotes: 2

Michael Antipin
Michael Antipin

Reputation: 3532

KeyboardEvent.KEY_DOWN is triggered by something in focus. Empty clip can not be in focus.

Reliable way for your situation is to subscribe to stage.

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);

Upvotes: 2

Related Questions