PDA

View Full Version : Can't remove objects from an array (pooling particles)


vonWolfehaus
06-02-2008, 05:18 AM
I can't use shift() or splice() and it's driving me insane:

var glength:int = gatActivePool.length;
for (var a:int = 0; a < glength; a+=1) {
var gatling:PBulletGat = gatActivePool[a];
if (gatling.dead) {
// If it's not already in the InactivePool, push it in
if (gatInactivePool.indexOf(gatling) < 0) gatInactivePool.push(gatling);
// Remove it from the ActivePool...
// CAUSES NULL OBJECT ERROR:
//gatActivePool.shift();
// SAME:
gatActivePool.splice(gatActivePool.indexOf(gatling ), 1); // doesn't work with splice(a, 1) either
} else {
gatling.update();
}
}

Elsewhere, in a shoot() method I have this:

var gat:Gat1 = gatInactivePool.shift();
gatActivePool.push(gat);
gat.spawn();

So while the player is shooting (adding to the active pool), the game will add the bullet back to the inactive pool if it leaves the screen. So there's a lot of shifting going on, which is why I figured I was getting a null return when I used splice() (hard to get an index position if the index keeps changing), so I tried shift instead to blindly remove the first element, but that didn't work either.

So does anyone have any idea why I can't remove anything from the gatActivePool array at all?

Or for that matter, is there a better way to recycle particles?

rrh
06-02-2008, 02:29 PM
One problem that strikes me is that the length of the array will be reduced every time you splice something out of the array, which will screw up your for loop.

One way to avoid this is to loop backwards through the loop.
for (var i:int=length-1;i>=0;--i) {


And you could also remove the old bullets and create new bullets as needed, rather than have an array of unused bullets.

vonWolfehaus
06-02-2008, 04:20 PM
You, Sir, are amazing. That did it.

The reason I want to avoid creating new bullets is because creation is expensive, computationally speaking. It would be more efficient to simply "recycle" the particles by turning their visibility off when "dead" and then turning them back on with new positions and rotations when needed again.

Unfortunately I have yet to perfect this system, as there seems to be a memory leak, but I'll find it eventually. It was the null error that had me stumped (for days, I kid you not--I'm no pro, obviously ;)). EDIT: Memory leak appears to be somewhere else in the code, not the particle system. So that's good :D

Again, thank you so much.