0

カスタム イベントと一緒にパラメータを送信するための簡単な (または推奨される) 方法はありますか? それとも、2 つのクラス間で変数を渡すだけの方法ですか?

私のプログラムは、単純な Civ/Age of Empires のようなゲームで、建物をタイルに配置できます。これは次のように機能します。

  • プレーヤーが HUD のアイコンをクリックすると、PLAYER クラスが受け取るイベントがディスパッチされます。
  • PLAYER クラスは、どの建物が保持されているか (クリックされたか) によって値が変わります。
  • プレーヤーがグリッド内のタイルをクリックして配置すると、PLAYER クラスが受け取るイベントが送出されます。
  • PLAYER クラスは建物オブジェクトを作成し、それを PLAYER クラス内の配列に追加します。

コードをどのように機能させたいかの例:

icon.as

private function onMouseClick(e:MouseEvent = null):void {
        var iconClickedEvent:Event = new Event("BUILDING_HELD", buildingType);  // passes "buildingType" through the event somehow
        stage.dispatchEvent(iconClickedEvent);
}

tile.as

private function onMouseClick(e:MouseEvent = null):void {
        var buildingPlacedEvent:Event = new Event("BUILDING_PLACED", xRef, yRef);// passes "xRef" & "yRef", the tile's co-ordinate
        stage.dispatchEvent(buildingPlacedEvent);
}

player.as

private function init(e:Event):void {
        stage.addEventListener("BUILDING_HELD", buildingHeld(buildingType));
        stage.addEventListener("BUILDING_PLACED", placeBuilding(xRef, yRef));
}

private function buildingHeld(building:int):void {
        buildingType = building;
}

private function placeBuilding(xRef:int, yRef:int):void {
        switch(buildingType){
                case 1: // main base
                        MainBaseArray.push();
                        MainBaseArray[length-1] = new MainBase(xPos, yPos);     // create new object with the references passed
                        break;
        }
}
4

1 に答える 1

1

これを管理する最善の方法は、イベント (またはイベント タイプ) ごとにカスタム イベント クラスを作成することです。Eventを継承するクラスを作成すると、標準の Event と同じように使用できますが、カスタム値またはメソッドを含めることができます。

そのようなクラスの例を次に示します。

public class BuildingEvent extends Event {

  // contains an event name. Usefull to ensure at compile-time that there is no mistape in the event name.
  public static const BUILDING_HELD:String = "BUILDING_HELD";

  private var _buildingType:int;

  // the constructor, note the new parameter "buildingType". "bubbles" and "cancelable" are standard parameters for Event, so I kept them. 
  public function BuildingEvent(type:String, buildingType:int, bubbles:Boolean = false, cancelable:Boolean = false) {
    super(type, bubbles, cancelable);
    _buildingType = buildingType;
  }

  // using a getter ensure that a listening method cannot edit the value of buildingType.
  public function get buildingType() {
    return _buildingType;
  }
}

次に、このクラスを次のように使用できます。

// to dispatch the event
private function onMouseClick(e:MouseEvent = null):void {
  var iconClickedEvent:BuildingEvent = new BuildingEvent(BuildingEvent.BUILDING_HELD, buildingType);
  stage.dispatchEvent(iconClickedEvent);
}

// to listen to the event
private function init(e:Event):void {
  stage.addEventListener(BuildingEvent.BUILDING_HELD, buildingHeld);
}
private function buildingHeld(event:BuildingEvent):void {
  buildingType = event.buildingType;
}
于 2014-05-09T08:14:35.847 に答える