0
//Main Class
package{
  public class Main extends MovieClip{
    private var bombCarrier:BombCarrier;
    private var building:Building;
    private var bomb:Bomb;
    public var buildingArray:Array;

    public function Main(){
      bombCarrier = new Carrier();
      addChild(bombCarrier);
      for(var i:int=0;i<5;i++){
        var xPosition:Number = i*105;
        building = new Building(xPosition, stage.stageHeight);
    addChild(building);
    buildingArray.push(building);
  }
      stage.addEventListener(Event.KeyboardEvent, keyDownFunction);
    }
    public function keyDownFunction(event:KeyboardEvent){
      if(event.keyCode == 70){
        bomb = new Bomb(bombCarrier.x, bombCarrier.y, 0.5);
        addChild(bomb);
      }
    }
  }
}

//Bomb Class
package{
  public class Bomb extends MovieClip{
    private var speed:Number;
    public function Bomb(x, y, speed){
      this.x = x;
      this.y = y;
      this.speed = speed;
      addEventListener(Event.ENTER_FRAME, loop);
    }
    public function loop(event:Event){
      this.y += speed;
      for(var i:int=0;i<Main(parent).buildingArray.length;i++){
        if(hitTestObject(Main(parent).buildingArray[i])){
          this.removeEventListener(Event.ENTER_FRAME, loop);
          Main(parent).buildingArray.splice(i, 1);
          parent.removeChild(this); //This line got Error
        }
      }
    }
  }
}

我尝试了很多方法,但我仍然得到相同的错误,即 TypeError:错误 #1009:无法访问空对象引用的属性或方法。在炸弹/循环()。我已经尝试使用命令行逐行调试,似乎只是这行代码“parent.removeChild(this);” 显示问题。

4

1 回答 1

1

看起来您试图多次移除炸弹(在 for 循环中)。所以在第一次之后,它不再是父母的孩子。

此外,您在将炸弹添加到舞台之前启动输入帧处理程序,因此在此之前 parent 将为空。

break;一旦你第一次移除了炸弹,你就会想要离开你的循环。

//Bomb Class
package{
  public class Bomb extends MovieClip{
    private var speed:Number;
    private var buildingArray:Array;

    public function Bomb(x, y, speed){
      this.x = x;
      this.y = y;
      this.speed = speed;
      addEventListener(Event.ADDED_TO_STAGE,addedToStage,false,0,true);
    }

    private function addedToStage(e:Event):void {
        buildingArray = Main(parent).buildingArray;  //it would be better to just pass it in the constructor
        addEventListener(Event.ENTER_FRAME, loop);
    }

    public function loop(event:Event){
      this.y += speed;
      for(var i:int=0;i<buildingArray.length;i++){
        if(hitTestObject(buildingArray[i])){
          this.removeEventListener(Event.ENTER_FRAME, loop);
          buildingArray.splice(i, 1);
          parent.removeChild(this);
          break; //get out of the loop
        }
      }
    }
  }
}

在效率方面,如果您在炸弹类中引用 buildingArray 会更快,因此您不必执行 Main(parent)。每次你需要访问它。

于 2012-08-31T16:38:07.200 回答