我在开始使用的游戏中无法正常使用KeyboardEvent时遇到问题。我有三个类,一个用于处理级别,一个是实际级别,一个代表虚拟角色:
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);
}
}
头像
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时,两个类都有所有软件包,但是如果在游戏执行过程中单击其他位置,焦点就会丢失,并且不再起作用。请任何人能帮助我吗?
提前感谢
键盘事件仅在分配给它们的对象是当前焦点时触发。
幸运的是,默认情况下stage
始终具有焦点。这意味着您可以将事件侦听器添加到舞台上,以始终按预期触发键盘事件:
stage.addEventListener(KeyboardEvent.KEY_DOWN, apertou);
您可以将密钥处理程序从化身移动到关卡或关卡,然后在其中移动化身。
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++;
}
}
}