AS3没有键盘输入注册

时间:2014-05-03 00:52:49

标签: actionscript-3 flash actionscript

所以我希望一个物体围绕另一个物体运行,但我希望它只在按下右箭头键时才能这样做。当我运行这个程序时,即使按下右箭头键并且它没有跟踪,轨道器也根本不会移动!

非常感谢任何帮助!

PS我是否必须使用KEY_DOWN的事件监听器,或者我可以返回一个号码并检查它吗?

var orbiter:Orbiter = new Orbiter();
var origin:Origin = new Origin();
var angle:Number = 0;
var speed:Number = 1.5;
var radius:Number = 75;
origin.x= 100;
origin.y =100;
addChild(orbiter);
addChild(origin);

stage.addEventListener(Event.ENTER_FRAME, Orbit_Brah);
function Orbit_Brah(event:Event):void
{
    var nLeftOrRight = CheckKeyDown;
    if (nLeftOrRight == 1)
    {
    angle += speed;
    var rad:Number = angle * (Math.PI / 180);
    orbiter.x = origin.x + radius * Math.cos(rad);
    orbiter.y = origin.y + radius * Math.sin(rad);
    orbiter.rotation = (Math.atan2(orbiter.y-origin.y, orbiter.x-origin.x) * 180 / Math.PI);
    }
}

function CheckKeyDown(event:KeyboardEvent):int
{
    if (event.keyCode == Keyboard.RIGHT)
    {
        trace ("Key Press Registered");
        return 1;
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您需要添加一个侦听器才能从KeyboardEvents中获取信息。将信息存储在变量中,并在更新循环中使用它。您可能还想使用KeyboardEvent.KEY_UP来检查何时释放键。这样的事情。

stage.addEventListener(Event.ENTER_FRAME, Update);
stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyboardDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, OnKeyboardUpHandler);

function Update(pEvent : Event) : void
{
    // update code here using stored info
    if(_isMovingRight)
    {
        //
    }
}

function OnKeyboardDownHandler(pEvent : KeyboardEvent) : void
{
    switch(pEvent.keyCode)
    {
        case Keyboard.RIGHT:
            _isMovingRight = true;
            break;
    }
}

function OnKeyboardUpHandler(pEvent : KeyboardEvent) : void
{
    switch(pEvent.keyCode)
    {
        case Keyboard.RIGHT:
            _isMovingRight = false;
            break;
    }
}

答案 1 :(得分:1)

你太努力了。声明后您需要做的就是:

stage.addEventListener(KeyboardEvent.KEY_DOWN, Orbit_Brah);


function Orbit_Brah(e)
{
    if (e.keyCode == Keyboard.RIGHT) 
    {
    angle += speed;
    var rad:Number = angle * (Math.PI / 180);
    orbiter.x = origin.x + radius * Math.cos(rad);
    orbiter.y = origin.y + radius * Math.sin(rad);
    orbiter.rotation = (Math.atan2(orbiter.y-origin.y, orbiter.x-origin.x) * 180 / Math.PI);
    }
}

这仍然会给你留下一个小的数学问题,这在你运行代码时会很明显,但你可以解决这个问题。