2011-05-03 59 views
1

我正在通過一本書(ActionScript 3.0設計模式,O'Reilly)中的Space Invaders示例進行工作,並且我已經弄清楚了事情,除非現在看到「可能未定義的方法」的原因

internal/space-invaders/trunk/ship/ShipFactory.as, Line 11 1180: Call to a possibly undefined method drawShip. 
internal/space-invaders/trunk/ship/ShipFactory.as, Line 12 1180: Call to a possibly undefined method setPosition. 
internal/space-invaders/trunk/ship/ShipFactory.as, Line 14 1180: Call to a possibly undefined method initShip. 

並且我還沒有模糊的想法爲什麼。範圍界定?糟糕的繼承?包裹可見度?我誤解了AS3的多態規則嗎?這裏(按順序)是基類,子類和工廠類:

基類Ship.as

package ship { 
    import flash.display.Sprite; 

    class Ship extends Sprite { 

     function setPosition(x:int, y:int):void { 
      this.x = x; 
      this.y = y; 
     } 

     function drawShip():void { } 

     function initShip():void { } 

    } 

} 

兒童類HumanShip.as

package ship { 
    import weapon.HumanWeapon; 
    import flash.events.MouseEvent; 

    class HumanShip extends Ship { 

     private var weapon:HumanWeapon; 

     override function drawShip():void { 
      graphics.beginFill(0x00ff00); 
      graphics.drawRect(-5, -15, 10, 10); 
      graphics.drawRect(-12, -5, 24, 10); 
      graphics.drawRect(-20, 5, 40, 10); 
      graphics.endFill(); 
     } 

     override function initShip():void { 
      weapon = new HumanWeapon(); 
      this.stage.addEventListener(MouseEvent.MOUSE_MOVE, this.moveShip); 
      this.stage.addEventListener(MouseEvent.MOUSE_DOWN, this.fire); 
     } 

     protected function moveShip(event:MouseEvent):void { 
      trace('MOVE'); 
      this.x = event.stageX; 
      event.updateAfterEvent(); 
     } 

     protected function fire(event:MouseEvent):void { 
      trace('FIRE'); 
      weapon.fire(HumanWeapon.MISSILE, this.stage, this.x, this.y - 25); 
      event.updateAfterEvent(); 
     } 

    } 

} 

工廠類ShipFactory.as

package ship { 
    import flash.display.Stage; 

    public class ShipFactory { 

     public static const HUMAN:uint = 0; 
     public static const ALIEN:uint = 1; 

     public function produce(type:uint, target:Stage, x:int, y:int):void { 
      var ship:Ship = this.createShip(type); 
      ship.drawShip(); 
      ship.setPosition(x, y); 
      target.addChild(ship); 
      ship.initShip(); 
     } 

     private function createShip(type:uint):Ship { 
      switch (type) { 
       case HUMAN: return new HumanShip(); 
       case ALIEN: return new AlienShip(); 
       default: 
        throw new Error('Invalid ship type in ShipFactory::createShip()'); 
        return null; 
      } 
     } 

    } 

} 

回答

1

唯一的那個ju對我來說mps是基地「Ship」類中的方法沒有訪問修飾符。嘗試明確地讓它們公開!我不確定如果沒有指定訪問修飾符,AS3默認是什麼,它們可能被視爲受保護。

+0

這是我的理解,默認修飾符是「internal」,這是我以前設置的。我會再用'public'去看看它是否改變了行爲。 – 2011-05-03 17:21:05

+0

這是一個消極的。將'顯式訪問修飾符添加到'Ship'方法(以及對'HumanShip'中的覆蓋)不起作用。 – 2011-05-03 18:58:21

+1

但是,由於Adobe的IntelliSense版本,我導致玩弄變量名稱。顯然AS3不喜歡它,因爲當你在類方法中命名臨時對象時,它與類出現的包相同。無論如何接受 - 感謝您的幫助! – 2011-05-03 19:06:35

相關問題