按下多个键时如何防止停止移动(ActionScript)

时间:2012-07-06 15:42:12

标签: flash actionscript

我有2个eventListeners:

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

2)键侦听器(WhiteSpace) - 用于跳转对象

所以,当我按下A OR S或D或W键时,我按下空格,在这一刻之前它的所有okey,对象同时移动和跳跃,但如果我在移动时释放空格键,物体停止......

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

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);


}

1 个答案:

答案 0 :(得分: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...
}

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