簡體   English   中英

鍵盤事件as3無法正常工作

[英]keyboard event as3 not working

在我弄明白之前,這讓我頭疼了2個小時。
我決定把它貼在這里,以幫助別人不要把頭發拉出來:)。

基本上這個錯誤是我沒有從我的Flash Builder環境中接收鍵盤事件(使用adobe flash cs5可以看到同樣的錯誤/問題)。 我設置了stage.focus = stage,沒有幫助。 我添加了其他事件監聽器(mouse_down,frame_enter)工作正常,我添加了MovieClip子項並聽取了這些孩子的事件,仍然是同樣的問題。

package
{
  public class Test extends Sprite 
  {

    public function Test() 
    {
        this.addEventListener(Event.ADDED_TO_STAGE,init);
    }

    public function init(stage:Stage):void 
    {
        this.removeEventListener(Event.ADDED_TO_STAGE,init);
        stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
        stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
    }


    private function keyPressed(e:KeyboardEvent):void 
    {
        trace("keyPressed");
    }

    private function keyReleased(e:KeyboardEvent):void 
    {
        trace("keyReleased");
    }
  }
}

使用鍵盤命令需要監聽鍵盤事件。 此過程與在AS3中偵聽任何其他事件的過程相同。 您需要使用addEventListener()方法向KeyboardEvent注冊。 但是,與其他對象不同,由於鍵盤不必附加到項目中的任何特定對象,因此鍵盤事件通常在舞台上注冊。 在下面的代碼中,stage對象注冊每次按下鍵盤鍵時觸發的鍵盤事件。

與AS2不同,在AS3中鍵盤事件不是全局的。 它們被發布到舞台上,並且它們通過顯示列表鼓泡到任何顯示對象具有焦點。

package
{
import flash.display.*;
import flash.events.*;

  public class Test extends Sprite 
  {
   public function Test() 
   {
     init();
   }

   public function init():void 
   {
      stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
      stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
   }


   private function keyPressed(e:KeyboardEvent):void 
   {
      trace("keyPressed");
   }

   private function keyReleased(e:KeyboardEvent):void 
   {
    trace("keyReleased");
   }
  }
}
public function init(stage:Stage):void 

ADDED_TO_STAGE is a `listener Event` not a stage instance. 

所以而不是stage:Stage使用event:Event

你需要導入所需的類。

標記改變的行。 你的代碼沒有編譯btw,檢查錯誤日志。

package  {

import flash.display.Sprite; /// changed line
import flash.events.Event; /// changed line
import flash.events.KeyboardEvent; /// changed line


public class Test extends Sprite 
{

public function Test() 
{
    this.addEventListener(Event.ADDED_TO_STAGE,init);
    /* i like it this way
    stage ? init(null) : addEventListener(Event.ADDED_TO_STAGE,init);
    */

}

public function init(e:Event):void  /// changed line
{
    this.removeEventListener(Event.ADDED_TO_STAGE,init);
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}


private function keyPressed(e:KeyboardEvent):void 
{
    trace("keyPressed");
}

private function keyReleased(e:KeyboardEvent):void 
{
    trace("keyReleased");
}
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM