将键盘事件更改为鼠标事件as3

时间:2017-10-13 09:29:10

标签: actionscript-3 flash mouseevent

我是一个学习动作脚本3的新人。

当我移动行走角色时,我将键盘事件转换为鼠标事件时出现问题。

使用键盘事件时我没有问题。这是我的代码

    import flash.ui.Keyboard;
    var speed:Number=2;
    stage.addEventListener(KeyboardEvent.KEY_DOWN, stikman);
    function stikman(e:KeyboardEvent)
     {
      if (e.keyCode==Keyboard.LEFT)
       {
        stik.x-=speed;
        stik.scaleX=-1;
        stik.stik2.play();
       }
      else if (e.keyCode==Keyboard.RIGHT)
       {
        stik.x+=speed;
        stik.scaleX=1;
        stik.stik2.play();
       }
      }

然后我尝试将键盘事件更改为鼠标事件时,使用按钮移动字符时应单击,单击并单击。我想在移动角色时按住鼠标,当鼠标向上移动角色时停止。但我还是不知道怎么做。这是我的代码,当我尝试更改为鼠标事件

     var speed:Number=2;
     mundur.addEventListener(MouseEvent.MOUSE_DOWN, stikman);
     function stikman(e:MouseEvent)
      {
       stik.x-=speed;
       stik.scaleX=-1;
       stik.stik2.play();
      }
     maju.addEventListener(MouseEvent.CLICK, stikman2);
     function stikman2(e:MouseEvent)
      {
        stik.x+=speed;
        stik.scaleX=1;
        stik.stik2.play();
      }

1 个答案:

答案 0 :(得分:2)

因为只要按下键,键盘就会重复产生 KeyboardEvent.KEY_DOWN 事件,而 MouseEvent.CLICK 以及 MouseEvent.MOUSE_DOWN 是每个用户操作仅调度一次。

使用鼠标,您需要更改逻辑。

// Subscribe both buttons.
ButtonRight.addEventListener(MouseEvent.MOUSE_DOWN, onButton);
ButtonLeft.addEventListener(MouseEvent.MOUSE_DOWN, onButton);

var currentSpeed:Number = 0;
var isPlaying:Boolean = false;

function onButton(e:MouseEvent):void
{
    // Set up the directions and start the animation.
    switch (e.currentTarget)
    {
        case ButtonLeft:
            currentSpeed = -speed;
            stik.stik2.play();
            stik.scaleX = -1;
            break;

        case ButtonRight:
            currentSpeed = speed;
            stik.stik2.play();
            stik.scaleX = 1;
            break;
    }

    isPlaying = true;

    // Call repeatedly to move character.
    addEventListener(Event.ENTER_FRAME, onFrame);

    // Hook the MOUSE_UP even even if it is outside the button or even stage.
    stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
}

function onFrame(e:Even):void
{
    // Move character by the designated offset each frame.
    stik.x += currentSpeed;

    if (!isPlaying)
    {
        // Stop at last frame.
        // if (stik.stik2.currentFrame == stik.stik2.totalFrames)

        // Stop at frame 1.
        if (stik.stik2.currentFrame == 1)
        {
            // Stop the animation.
            stik.stik2.stop();

            // Stop moving.
            removeEventListener(Event.ENTER_FRAME, onFrame);
        }
    }
}

function onUp(e:MouseEvent):void
{
    // Indicate to stop when the animation ends.
    isPlaying = false;

    // Unhook the MOUSE_UP event.
    stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
}