Search code examples
actionscript-3flashvectorcollision-detection

Splicing elements out of a Vector in a loop which goes through the same Vector (ActionScript 3)


I'm making a simple game and have a Vector full of enemies in order to do hit-checking on them from my "laser" object (it's a space shmup). Every laser loops through the Vector and checks if it's occluding the hit circle. The problem lies in when one laser destroys an enemy, the rest of the lasers try to also check the same Vector, only to go out of bounds since the enemy's already been spliced out and it's changed the size of the Vector.

for each (var enemy:Enemy in enemies){
                var distanceX = this.x - enemy.x;
                var distanceY = this.y - enemy.y;
                var distance = Math.sqrt( (distanceX*distanceX) + (distanceY*distanceY) );

                if (distance <= enemy.hitRadius) {
                    enemy.removeEnemy();
                    enemies.splice(enemies.indexOf(enemy),enemies.indexOf(enemy));
                }
}

How would I go about collecting the index of individual elements in the Vector to be deleted, then only deleting them when every Laser object is finished its checking?

edit: here's my removeEnemy() function from my Enemy class, just in case:

public function removeEnemy(){
            removeEventListener(Event.ENTER_FRAME, move);
            parent.removeChild(this);
            trace("removed Enemy", enemies.indexOf(this));
        }

edit edit: I'm also getting a null reference pointer error to "parent" in my removeEnemy() function... but only sometimes. I have a feeling that if I fix one of these two problems, the other will also be fixed but I'm not sure.


Solution

  • I fixed it! The problem was actually in how I used the "splice()" method. Turns out that the second parameter isn't the end index of where to stop splicing, it's the number of elements to be spliced. So when I was trying to splice element 0, I wasn't splicing anything, and when I was trying to splice element 3, I was also splicing 4 and 5. I feel like such a dunce for not reading the API right and wasting a couple hours on this. Thanks to everyone who commented-- you guys helped me rule out what I thought the problem was.