2011-11-02 41 views
1

我剛開始學習AS3。如何檢測as3中的多個按鍵事件?

假設我的精靈上有兩個文本框。

當我按下左或右箭頭鍵時,我喜歡移動文本框1,但我也想移動textfield 2,當我按下空格時,文本框1正在移動,如...一個電子遊戲遊戲(您可以拍攝導彈,同時你正在移動)。

我真的很喜歡發佈我的源代碼......但我實際上不知道從哪裏開始。

下面的代碼移動文本字段1當我按下箭頭鍵...

我的代碼片段:

private function keyHandler(event:KeyboardEvent):void 
{ 

    switch(event.keyCode) 
    { 
     case 38: 
      this._txt.y -= 10; 
      break; 
     case 40: 
      this._txt.y += 10; 
      break; 

     case 39: 
      this._txt.x += 10; 
      break; 
     case 37: 
      this._txt.x -= 10; 
      break; 
    } 


} 
+0

那麼,有什麼不工作? –

+0

@Laurent //一切工作正常....我認爲www0z0k已經回答了我的問題。 – Moon

回答

10
package { 
    import flash.display.Sprite; 
    import flash.events.Event; 
    import flash.events.KeyboardEvent; 
    import flash.ui.Keyboard; 
    /** 
    * ... 
    * @author www0z0k 
    */ 
    public class KeyExample extends Sprite { 
     private var _theyArePressed:Object = { }; 
     public function KeyExample() { 
      if (stage) init(); 
      else addEventListener(Event.ADDED_TO_STAGE, init); 
     } 

     private function init(e:Event):void { 
      removeEventListener(Event.ADDED_TO_STAGE, init); 
      stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown); 
      stage.addEventListener(KeyboardEvent.KEY_UP, onUp);   
     } 

     private function onUp(e:KeyboardEvent):void { 
      _theyArePressed[e.keyCode] = false; 
     } 

     private function onDown(e:KeyboardEvent):void { 
      _theyArePressed[e.keyCode] = true; 
      if (_theyArePressed[Keyboard.SPACE] && _theyArePressed[Keyboard.UP]) { 
       //do anything 
      } 
     }  
    } 
} 

但請記住,據我所知鍵盤可以處理的按鍵數量有限在同一時間按下,取決於硬件

+0

謝謝...這正是我所尋找的 – Moon

+0

僅供參考,我建議你有一個專門的,可重用的關鍵類。 – apscience

+0

這只是一個例子,它應該存儲像'{keyCodes:[],functionReference:functionName}這樣的對'並檢查它們'onDown'是可重用的 – www0z0k