2013-03-17 145 views
0

我在開始製作KeyboardEvent的遊戲時遇到問題。我有三個班,一個用於處理水平,一個是實際的水平,一個代表形象:Flash上​​的KeyboardEvent無法正常工作

級別

import flash.display.MovieClip; 
import flash.events.Event; 

public class Fase extends Cena 
{ 
    var avatar:Avatar; 

    public function Fase() 
    { 
     // constructor code 
     this.addEventListener(Event.ADDED_TO_STAGE, onAdded); 
    } 

    public function onAdded(e:Event) 
    { 
     avatar = new Avatar(); 
     this.addChild(avatar); 
     avatar.x = stage.width/2; 
     avatar.y = 30; 

    } 

    public function die() 
    { 
     this.removeEventListener(Event.ADDED_TO_STAGE, onAdded); 
     (this.parent as ScreenHandler).removeChild(this); 
    } 

} 

阿凡達

public class Avatar extends MovieClip 
{ 

    public function Avatar() 
    { 
     // constructor code 
     this.addEventListener(Event.ADDED_TO_STAGE, onAdded); 
    } 

    public function onAdded(e:Event) 
    { 
     //stage.focus=this; 
     this.addEventListener(KeyboardEvent.KEY_DOWN, apertou); 
    } 

    public function apertou(event:KeyboardEvent) 
    { 
     trace("o"); 
     if(event.keyCode == Keyboard.LEFT) 
     { 
      this.x++; 
     } 
    } 

} 

我有如果我在頭像上使用stage.focus = this,則兩個類上的所有包都可以工作,但如果在遊戲執行過程中單擊其他位置,焦點將丟失,並且不再有效。請任何人都可以幫我嗎?

在此先感謝

回答

1

鍵盤事件僅當它們分配給的對象是當前焦點時纔會觸發。

幸運的是,默認情況下stage總是有焦點。這意味着你可以添加你的事件偵聽器的階段總是有鍵盤事件觸發按預期:

stage.addEventListener(KeyboardEvent.KEY_DOWN, apertou); 
+0

謝謝馬蒂,問題解決了! =) – 2013-03-18 11:10:13

0

您可以從化身的水平或階段移動鍵處理程序,然後將你的頭像在那裏。

public class Fase extends Cena 
{ 
    var avatar:Avatar; 

    public function Fase() 
    { 
     // constructor code 
     this.addEventListener(Event.ADDED_TO_STAGE, onAdded); 
    } 

    public function onAdded(e:Event) 
    { 
     avatar = new Avatar(); 
     this.addChild(avatar); 
     avatar.x = stage.width/2; 
     avatar.y = 30; 
     addEventListener(KeyboardEvent.KEY_DOWN, apertou); 

    } 

    public function die() 
    { 
     this.removeEventListener(Event.ADDED_TO_STAGE, onAdded); 
     (this.parent as ScreenHandler).removeChild(this); 
    } 

    public function apertou(event:KeyboardEvent) 
    { 
     if(event.keyCode == Keyboard.LEFT) 
     { 
      avatar.x++; 
     } 
    } 

} 
+0

謝謝您的回答,但仍只與班上stage.focus具有鍵盤代碼工作。 – 2013-03-18 01:35:06