0

是否有任何简单(或建议)的方法可以将参数与自定义事件一起发送?甚至只是一种在两个类之间传递变量的方法?

我的程序是一种简单的 Civ/Age of Empires 游戏,您可以在其中将建筑物放置在瓷砖上。这将按如下方式工作:

  • 玩家单击 HUD 上的图标,这会创建一个调度事件,该事件由 PLAYER 类接收。
  • PLAYER 类根据持有(点击)的建筑物更改值。
  • 玩家单击网格中的图块来放置它,这会调度一个由 PLAYER 类接收的事件。
  • PLAYER 类创建一个建筑对象并将其添加到 PLAYER 类中的一个数组中。

我希望代码如何工作的一个例子:

图标.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);
}

瓷砖.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);
}

播放器.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 回答