Pedro Henrique
Pedro Henrique

Reputation: 619

How to correctly use KeyboardEvent on Flash

I have a problem making a KeyboardEvent work in the game I'm starting. I have three classes, one for handling the levels, one that is the actual level and one to represent the avatar:

Level

import flash.display.MovieClip;
import flash.events.Event;

public class Fase extends Cena
{
    var avatar:Avatar;

    public function Fase()
    {
        // constructor code
        this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
    }

    public function onAdded(e:Event)
    {
        avatar = new Avatar();
        this.addChild(avatar);
        avatar.x = stage.width/2;
        avatar.y = 30;

    }

    public function die()
    {
        this.removeEventListener(Event.ADDED_TO_STAGE, onAdded);
        (this.parent as ScreenHandler).removeChild(this);
    }

}

Avatar

public class Avatar extends MovieClip
{

    public function Avatar()
    {
        // constructor code
        this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
    }

    public function onAdded(e:Event)
    {
        //stage.focus=this;
        this.addEventListener(KeyboardEvent.KEY_DOWN, apertou);
    }

    public function apertou(event:KeyboardEvent)
    {
        trace("o");
        if(event.keyCode == Keyboard.LEFT)
        {
            this.x++;
        }
    }

}

I have all the packages on both classes an all works if I use the stage.focus=this on the Avatar, but if I click somewhere else during game excecution the focus is lost and it doesn't work anymore. Please can anyone help me?

Thanks in advance

Upvotes: 0

Views: 126

Answers (2)

Marty
Marty

Reputation: 39458

Keyboard events only trigger when the object they're assigned to are the current focus.

Fortunately, the stage always has focus by default. This means you can add your event listeners to the stage to always have the keyboard events trigger as expected:

stage.addEventListener(KeyboardEvent.KEY_DOWN, apertou);

Upvotes: 1

Barış Uşaklı
Barış Uşaklı

Reputation: 13510

You can move the key handler from the avatar to the level or stage and then move your avatar in there.

public class Fase extends Cena
{
    var avatar:Avatar;

    public function Fase()
    {
        // constructor code
        this.addEventListener(Event.ADDED_TO_STAGE, onAdded);
    }

    public function onAdded(e:Event)
    {
        avatar = new Avatar();
        this.addChild(avatar);
        avatar.x = stage.width/2;
        avatar.y = 30;
        addEventListener(KeyboardEvent.KEY_DOWN, apertou);

    }

    public function die()
    {
        this.removeEventListener(Event.ADDED_TO_STAGE, onAdded);
        (this.parent as ScreenHandler).removeChild(this);
    }

    public function apertou(event:KeyboardEvent)
    {
        if(event.keyCode == Keyboard.LEFT)
        {
            avatar.x++;
        }
    }

}

Upvotes: 0

Related Questions