我是AS3的新手,如果这是完全基本的东西,请道歉,但我无法从我的代码中获得任何输出。我正在尝试制作Flash游戏并尝试测试此代码段以确保Flash正在接收用户的键盘输入。如上所述,我没有得到任何错误,但我也没有在输出窗口中得到任何东西。我敢肯定我错过了其他人明显的东西。如果有人知道可能出现什么问题,我将非常感激。 这是代码:
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.events.KeyboardEvent;
function keyDownHandler(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
trace("left pressed");
}
else if(event.keyCode == Keyboard.RIGHT)
{
trace("right pressed");
}
else if(event.keyCode == Keyboard.UP)
{
trace("up pressed");
}
else if(event.keyCode == Keyboard.DOWN)
{
trace("down pressed");
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
}
function keyUpHandler(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
trace("left released");
}
else if(event.keyCode == Keyboard.RIGHT)
{
trace("right released");
}
else if(event.keyCode == Keyboard.UP)
{
trace("up released");
}
else if(event.keyCode == Keyboard.DOWN)
{
trace("down released");
}
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
}
答案 0 :(得分:2)
您的侦听器永远不会注册,您可以在密钥处理程序函数中使用它们,这当然不会在没有侦听器的情况下触发,因此不会注册侦听器。您必须将它们移出功能块。
答案 1 :(得分:0)
试试这段代码:
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.events.KeyboardEvent;
function keyDownHandler(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
trace("left pressed");
}
else if(event.keyCode == Keyboard.RIGHT)
{
trace("right pressed");
}
else if(event.keyCode == Keyboard.UP)
{
trace("up pressed");
}
else if(event.keyCode == Keyboard.DOWN)
{
trace("down pressed");
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
function keyUpHandler(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
trace("left released");
}
else if(event.keyCode == Keyboard.RIGHT)
{
trace("right released");
}
else if(event.keyCode == Keyboard.UP)
{
trace("up released");
}
else if(event.keyCode == Keyboard.DOWN)
{
trace("down released");
}
}
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
让我知道这是否有效。