2017-10-13 138 views
-1

我是誰學習動作腳本3.改變鍵盤事件,鼠標事件AS3

我有問題,當我的鍵盤事件轉換爲鼠標事件,當我移動行走人物新的新人。

使用鍵盤事件時我沒有問題。這是我的代碼

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

回答

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); 
} 
+0

感謝您的回答,先生,其權利。但是當鼠標向上時,我希望角色仍然走路,然後停在第一個位置。你能再幫我一次嗎? –

+0

@BagasPR然後不要退訂Event.ENTER_FRAME,也不要停止動畫。 – Organis

+0

我在先生之前嘗試過,但我仍然無法做到這一點。我不明白你的意思,因爲我對此仍然陌生:D。你能解釋一下嗎?當鼠標放下角色走路,並且當鼠標移動角色仍然走路直到幀結束,然後返回並停止到第一幀(第一個位置)。在此之前感謝 –