key_down延迟动作脚本3

时间:2014-05-10 08:22:00

标签: actionscript-3 actionscript delay keyboard-events

当您按下键时首先按下下一个按键是延迟但我不知道为什么。

           public function KeyboardControl(event:KeyboardEvent):void
    {
        keySpeed=5

        if(event.keyCode==Keyboard.RIGHT||event.keyCode==Keyboard.D)
        {
            if(_Vx<0)
            {
                _Vx=0;
            }
            _Vx += (keySpeed/mass);
        }
        if(event.keyCode==Keyboard.LEFT||event.keyCode==Keyboard.A)
        {
            if(_Vx>0)
            {
                _Vx=0;
            }
            _Vx -= (keySpeed/mass);
        }
             }

1 个答案:

答案 0 :(得分:1)

对于更具响应性的行为,请按以下方式构建:

private var _Vx:Number = 0;
private var keySpeed:Number = 5;
private var mass:Number = 10;

private var isKeyDown:Boolean;

private function init():void
{
  addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}

private function addedToStageHandler(event:Event):void
{
  removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);

  addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
  addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
  addEventListener(Event.ENTER_FRAME, update);
}

// Set the direction according to the key pressed
private function keyDownHandler(event:KeyboardEvent):void
{
  isKeyDown = true;

  if(event.keyCode == Keyboard.RIGHT || event.keyCode == Keyboard.D)
  {
    directionX = 1;
  }
  if(event.keyCode == Keyboard.LEFT || event.keyCode == Keyboard.A)
  {
    directionX = -1;
  }
}

private function keyUpHandler(event:KeyboardEvent):void
{
  isKeyDown = false;
}

// Game loop
private function update(event:Event):void
{
  if(isKeyDown)
  {
    if(_Vx<0)
    {
      _Vx=0;
    }
    _Vx += (keySpeed/mass) * directionX;
  }
}