我有一个问题就是在我正在开始的游戏中使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++;
}
}
}
如果我在“阿凡达”中使用stage.focus = this,我将两个类中的所有包都打包,但是如果我在游戏执行期间点击其他位置,则焦点会丢失,并且它不再起作用。请有人帮帮我吗?
提前致谢
答案 0 :(得分:1)
键盘事件仅在分配给它们的对象是当前焦点时触发。
幸运的是,stage
默认始终具有焦点。这意味着您可以将事件侦听器添加到舞台,以便始终按预期触发键盘事件:
stage.addEventListener(KeyboardEvent.KEY_DOWN, apertou);
答案 1 :(得分: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++;
}
}
}