//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);”显示问题。
答案 0 :(得分:1)
看起来你试图多次移除炸弹(在for循环中)。因此,在第一次之后,它不再是父母的孩子。
此外,在将炸弹添加到舞台之前启动输入框处理程序,因此在此之前父级将为空。
一旦你第一次取下炸弹,你就会想要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(父)。每当你需要访问它时。