2014-04-17 83 views
0

下午好。如果物品在舞台上从舞台上移除多个孩子

我正在制作游戏,在游戏中,如你所知,当你摧毁一个物体时,你必须将它从舞台上移除。

我的敌人通过代码动态添加,如果用户返回,敌人仍然会在显示列表中。

我试图通过尝试此代码删除敌人。

  removeChild(character); /removes player 

      removeChild(ground); // removes ground 

childrenOnStage是一个数字,等于this.numChildren

  for (var b:int = 0; b < childrenOnStage; b++) 
      { 
       if (getChildAt(b).name == "enemy") 
       { 
        removeChild(getChildAt(b)); 
       } 

      } 

当用户可以追溯到从游戏的主菜单,运行这段代码。

虽然代码会循环播放舞台上的所有孩子,但应该删除名称为敌人的代码。

但我得到一个错误

[Fault] exception, information=RangeError: Error #2006: The supplied index is out of bounds. 

我的问题是,我怎么可以删除这些敌人?

如果敌人被移除了,会造成更多错误,比如“空对象”,即敌人不在舞台上,那么为什么我应该把这个敌人移走呢?

谢谢。

更新由于Chernivs回答

 //after adding all of the children, this must be updated last 
     childrenOnStage = this.numChildren; 


    private function fromLevtoStart(e:MouseEvent):void 
    { 
     if (e.target == backBtn1) 
     { 
      stage.removeEventListener(Event.ENTER_FRAME, level1) 
      stage.addEventListener(Event.ENTER_FRAME, mainGameLoop) 
      //container.removeChild(_character); 
      removeChild(character); 
      removeChild(ground); 
      for (var b:int = 0; b < childrenOnStage; b++) 
      { 
       if (getChildAt(b).name == "enemy") 
       { 
        removeChild(getChildAt(b)); 

        //childrenOnStage --; 
              //update the variable below 
        childrenOnStage = this.numChildren; 


       } 

      } 
      this.gotoAndStop("Start"); 
     } 
    } 

这仍然没有消除所有的敌人,但只有一个出于某种原因。

它应该循环所有在舞台上有名字的敌人并将其移除,但它不会。

在尝试下面的内容之后,我可以说它只会移除名为“敌人”和typ Goblin的goblin1。

 goblin1 = new Goblin(); 
     goblin1.name = "enemy"; 

     goblin2 = new Goblin(); 
     goblin2.name = "enemy"; 

当我杀goblin1它被删除,那么当我回到开始界面妖精2不即使这剩下的名字唯一的妖精“敌人”它只是似乎goblin1的针对性一些原因。

回答

1

而不是检查name属性,检查显示对象的类型。例如:

if(getChildAt(b) is Goblin) { 
    //remove 
} 
+0

同样的事情发生,它只会删除goblin1。 – Moynul

+0

每当你移除一个妖精时,减少'b'为1. – Zhafur

+0

我明白了为什么现在,谢谢你减去b,所以我们可以将这个敌人从循环中减去,所以它可以搜索更多。谢谢你,大家好! – Moynul

1

基本上,减少变量应该工作。但是,如果你和你已经删除了任何问题,你可以这样做:

var enemies:Array = new Array(); 
for (var b:int = 0; b < childrenOnStage; b++) { 
    var child:DisplayObject = getChildAt(b); 
    if (child.name == "enemy") { 
     enemies.push(child); 
    } 
} 

trace(enemies); 

看看你。循环播放enemies并删除它们中的每一个 - 这样,您就不需要减少任何变量,也不需要考虑numChildren - 只需删除标记为敌人的所有内容即可。

+0

谢谢,但这只能消除一个敌人。自从我将两个敌人命名为“敌人”以来,我没有看到这个问题。 – Moynul

+0

goblin1 = new Goblin(); \t \t \t goblin1.name =“enemy”; \t \t \t \t \t \t goblin2 = new Goblin(); \t \t \t goblin2.name =“enemy”; – Moynul

+0

这就是为什么你应该跟踪数组并检查发生了什么。如果数组中包含单个项目 - 这意味着命名会出错。 @ Zhafur的答案有更好的检查,你也可以试试 –