0

我在开始的游戏中使 KeyboardEvent 工作时遇到问题。我有三个类,一个用于处理关卡,一个是实际关卡,一个用于表示头像:

等级

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);
    }

}

阿凡达

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++;
        }
    }

}

如果我在 Avatar 上使用 stage.focus=this,我在这两个类上都有所有的包,但如果我在游戏执行期间单击其他地方,焦点就会丢失并且不再起作用。请问有人可以帮我吗?

提前致谢

4

2 回答 2

1

键盘事件仅在分配给它们的对象是当前焦点时触发。

幸运的是,stage默认情况下总是有焦点。这意味着您可以将事件侦听器添加到阶段,以始终按预期触发键盘事件:

stage.addEventListener(KeyboardEvent.KEY_DOWN, apertou);
于 2013-03-18T01:35:13.923 回答
0

您可以将键处理程序从化身移动到关卡或舞台,然后将您的化身移动到那里。

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++;
        }
    }

}
于 2013-03-17T23:20:52.270 回答