Search code examples
actionscript-3eventsflashdevelop

Why doesn't my KEY_DOWN event fire?


I am new to ActionScript and was following the tutorial here to get me started using FlashDevelop. I set it up to move the item every KEY_DOWN event instead of using the frame event but my KEY_DOWN event is never fired. I quickly added a MOUSE_DOWN event to test the extent of the problem which works.

I am adding the listeners as my Paddle (an extension of Sprite) item is added to the stage:

private function addedToStage(e:Event) : void {
    // Remove this event listener
    removeEventListener(Event.ADDED_TO_STAGE, addedToStage);

    // Add the picture
    addChild(pic);

    // Set the location of the item in the middle of the screen one
    // height length of the image down.
    this.y = this.height;
    this.x = (this.stage.stageWidth - this.width) / 2;

    // Add the keyboard listener (broken).
    stage.addEventListener(KeyboardEvent.KEY_DOWN, this.keyDownHandler, false, 0, true);

    // Add the mouse listener (works).
    stage.addEventListener(MouseEvent.MOUSE_DOWN, this.mouseDown, false, 0, true);

    // Set the focus to the stage.
    stage.focus = stage;
}

I have a breakpoint in my keyDownHandler function and it is never called.

This may be a duplicate of this question, but I am already doing what the answer in that question describes and in the comments he explains that he does not know what fixed the problem only that it suddenly started working.

Another popular answer to that question mentions this article which is why there is a line in my code to set the focus back to the stage. There is nothing else on my stage.

What could be happening?

Edit:

Here is my listener code:

private function keyDownHandler(e:KeyboardEvent):void {
    var increment:Number; // Here is my breakpoint
    if (e.keyCode == 65 || e.keyCode == 37) {
        increment = -5;
    } else if(e.keyCode == 68 || e.keyCode == 39) {
        increment = 5;
    }
    var newX:Number = this.x + 5;
    if (newX > 0 && newX + this.width < this.stage.width) {
        this.x = newX;
    }
}

Solution

  • The problem was unrelated to the event itself, but rather how I was testing to see if it fired. You cannot place breakpoints on declarations.

    FlashDevelop will allow you to set a breakpoint there but the debugger will not actually stop at this point.

    The code to move the paddle does not work (not surprising to me at this point), but if I move the breakpoint to the line in the if statement (or any other line when an actual action performed such as the trace) suddenly it breaks fine. Now that I think about it even the other languages I've worked with have this behavior, I'm just too pampered by IDE's that will move the breakpoint to the nearest available line in such situations.