0

我有 2 个事件监听器:

1)关键监听器(A,S,D,W);- 用于移动对象

2) key listener(WhiteSpace) - 用于跳转对象

因此,当我按下 A OR S OR D OR W 键时,我按下空格键,在此之前一切正常,对象同时移动和跳跃,但如果我在移动时释放空格键,对象停...

那么当我释放键空白时,我怎么能做到这一点,对象仍然会移动?不注意其他键的释放或按下?

private function onKeyDown(e:KeyboardEvent):void {

    //trace(e.keyCode);
    switch(e.keyCode)
    {

    case 68:
    direction = 'left';
    stage.addEventListener(Event.ENTER_FRAME, moveRight);
    break;
    case 65:
    direction = 'right';
    stage.addEventListener(Event.ENTER_FRAME, moveLeft);
    break;
    case 32:
    jump() // the whitespace key
        break;

    }

private function moveRight(e:Event):void {

shape.x += 5;

}

private function moveLeft(e:Event):void {

shape.x += 5;

}

private function jump():void {

    stage.addEventListener(Event.ENTER_FRAME, jumpAnimation);
}

private function jumpAnimation(e:Event):void {

   //here code for jumping increasing the y and decreasing....
}

private function onKeyUp(e:Event):void {


    stage.removeEventListener(Event.ENTER_FRAME, moveRight);
    stage.removeEventListener(Event.ENTER_FRAME, moveLeft);


}
4

1 回答 1

1

您可以实现一个按键向上/向下监听器和一个输入帧监听器,并使用一些布尔值来指示哪些键被按下并相应地更新。像这样的东西可能会起作用:

var keyMap:Dictionary = new Dictionary();

addEventListener( KeyboardEvent.KEY_DOWN, onKeyDown );
addEventListener( KeyboardEvent.KEY_UP, onKeyUp );
addEventListener( Event.ENTER_FRAME, onEnterFrame );

function onKeyDown( event:KeyboardEvent ):void 
{
    keyMap[ event.keyCode ] = true;
}

function onKeyUp( event:KeyboardEvent ):void 
{
    keyMap[ event.keyCode ] = false;
}

function onEnterFrame( event:EnterFrame ):void 
{
    if( keyMap[ 68 ] ) 
    {
        // -- move left
    }

    if( keyMap[ 65 ] ) 
    {
        // -- move right 
    }

    // -- ect...
}

这将避免一个键向上导致所有其他键连续触发的情况,因为您只依赖于每个键向上或向下的单个键。更新场景的代码将连续运行。

于 2012-07-06T16:14:37.660 回答