0

I have two arrays, fireballs and gombas (enemies). When I create fireball and gomba, I add them into arrays using push();

I shoot fireballs and move gombas using foor loop

for (var f:int = 0; f < fireballs.length; f++)
{
    // move fireballs
}

I also remove fireballs if it goes too far, for example

if (myFireball.x + 1000 < player.x)
{
    if (myFireball.parent)
    {
        myFireball.parent.removeChild(myFireball);
        fireballs.splice(myFireball, 1);
    }
}

I have no problem removing fireballs, but if fireball hitTestObject gomba, I want to remove both, fireball and gomba, ant thats my problem.

I tried on this way and I get error, a term is undefined and has no properties

for (i = 0; i < fireballs.length; i++)
{
    for (var m = 0; m < gombas.length; m++)
    {
        if (fireballs[i].hitTestObject(gombas[m]))
        {
        if (fireballs[i].parent)
            {
                fireballs[i].parent.removeChild(fireballs[i]);
                // same for gombas
            }
        }
    }
}

If I use same loop but just check if fireballs and gombas are visible, if fireballs hit gombas I set visible to false and it works ok. Why it wont work with removeChild.

4

1 回答 1

0

正如@itcouldevenbeaboat 所说,在遍历数组并删除对象时,最好向后循环;这样,您就不会遇到索引问题。

例如,对于数组["one","two","three"],如果您像这样循环并删除:

for( var i:int = 0; i < myArray.length; i++ )
    myArray.splice( i, 1 );

发生了什么,是这样的:

  • i开始于0,指向"one"
  • 0我们从位置移除对象myArray
  • myArray就是现在["two","three"]
  • 在循环结束时,i递增,并变为1
  • 我们开始下一个迭代,并且iis 1,它指向"three"

在这个例子中,我们跳过了"two"字符串,因为splice它修改了我们正在迭代的数组。如果我们倒退:

for( var i:int = myArray.length - 1; i >= 0; i-- )
    myArray.splice( i, 1 );

然后我们得到这个:

  • i开始于2,指向"three"
  • 2我们从位置移除对象myArray
  • myArray就是现在["one","two"]
  • 在循环结束时,i递减,变为1
  • 我们开始下一个迭代,并且iis 1,它指向"two"

因此,我们从 中删除所有对象myArray,没问题。

对于您的特定示例,当您从两个数组中删除对象时,您应该向后迭代,这应该会给您类似:

outer: for ( var i:int = fireballs.length - 1; i >= 0; i-- )
{
    for ( var m:int = gombas.length - 1; m >= 0; m-- )
    {
        if (fireballs[i].hitTestObject(gombas[m]))
        {
            // remove our fireball and gombas graphics
            if( fireballs[i].parent != null )
                fireballs[i].parent.removeChild( fireballs[i] );
            if( gombas[m].parent != null )
                gombas[m].parent.removeChild( gombas[i] );

            // remove the fireball and gombas from the array; this is assuming
            // that once a fireball hits a gomba, they both disappear
            gombas.splice( m, 1 );
            fireballs.splice( i, 1 );

            // break to the outer loop; the fireballs one, as we don't need
            // to go any further in the inner one
            break outer;
        }
    }
}

注意循环outer上的标签;一旦我们检测到 a和 afireballs之间的碰撞,这让我们跳出来。fireballgomba

如果您想 afireball命中多个gombas,则不要删除图形或拼接数组。

于 2013-09-18T21:29:49.903 回答