unsure how to remove objet from stage & it's arrays after collision detected

Go To StackoverFlow.com

0

The scenario: in Main, instances of class Bullet are spawned and added to the stage, and to the array bltarray, instances of class Enemy are spawned, added to the stage, and added to nmearray. This works fine.

The problem comes in seemingly sporadically, i.e. it works, then suddenly doesn't work soon after, when it doesn't work I get spammed with output errors and the score display is constantly rising, note it's the same instance of bullet and enemy.

Bullet instance98 hit Enemy instance45
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at Main/everyframe()
Bullet instance98 hit Enemy instance45
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at Main/everyframe()

What I don't understand is,

The code I'm using is below (also in main)

for (var j=0;j<bltarray.length;j++){
    if (bltarray[j].hitTestObject(nmearray[i])){
        trace("Bullet "+bltarray[j].name+" hit Enemy "+nmearray[i].name);
            score += 1;
            scorevalue.text = score.toString();
            // Remove dead objects from stage
            stage.removeChild(nmearray[i]);
            stage.removeChild(bltarray[j]);
            // Remove reference to objects from array
            nmearray.splice(i,1);
            bltarray.splice(j,1);
            trace('nmearray length:'+nmearray.length)
    }
}

The bullet and enemy classes both have their own REMOVED_FROM_STAGE event listeners to remove other event listeners.

While I'm at it, this error occasinoally pops up too.

TypeError: Error #2007: Parameter hitTestObject must be non-null.
at flash.display::DisplayObject/_hitTest()
at flash.display::DisplayObject/hitTestObject()
at Main/everyframe()
2012-04-03 22:15
by Paine


0

Looks like you might encountering a common problem when splicing during a for loop. Basically, when you splice an element from an array the next element immediately gets pushed up to that location, causing your for loop to not actually check every element.

Try switching your for loop to a reverse for loop and see what happens:

for (var j=bltarray.length-1;j >= 0;j--){
//do stuff
}

Edit: fixed the for loop to be length-1

2012-04-03 22:31
by Pixel Elephant
TypeError: Error #1010: A term is undefined and has no properties. at Main/everyframe()

I'll put this into an if statement to ignore it when it's 0 and see if that helps.. - Paine 2012-04-03 22:51

@Paine Sorry, silly mistake - should be var j=bltarray.length- - Pixel Elephant 2012-04-03 23:03