Phaser Sprite.destroy()

I’ve been messing around with Phaser lately and it turned out to be an amazing game development library. I was always keen on using my on tech on everything I worked as it seemed easier to manage (“i know where everything is and what everything does” argument and similar nonsense) but Phaser really stands out for it’s simplicity, and what it offers. For a price of 0!

Anyway, while I mostly embraced Phaser’s concepts I cannot agree with the recycling sprites theory, telling me to kill() sprites and reuse them. So I should create multiple objects, add them to groups and then call kill() method on them when I don’t need them anymore and reuse them later (reset() method in conjunction with getFirstDead() method). While this sounds pretty straightforward and somewhat logic I disagree with it.

I am using multiple objects of same “class” but with various types (let’s say red, blue and yellow cars) and if I use kill() method on them I still need to cycle through all dead cars and get first red car if I wanna reuse red car. This seems kind of overkill – why would I wanna do that if I can simply create new red car and be done with it, not worrying about if I have any red car to in a pool of dead red cars to reuse.

So I simply went and used destroy() on the cars I wanted to destroy (let’s say in a game.physics.arcade.overlap() callbacks) and got various undefined errors, because of the way loops through objects in Phaser happen. When I want to destroy objects from various arrays and list I go from the last to first index and remove stuff designated to be destroyed, not fearing I’ll run out of bounds (removing objects from arrays while going from 0 index to size – 1 will quickly produce out of bounds errors), but Phaser loops (for overlaps, rendering, updates, etc.) work from index 0 to last, which is logical, the way they are meant to. So if I remove something from object arrays on the run stuff like out of bounds indexes and similar occur relatively quickly.

So in order to DESTROY something from object groups I called the kill() method on regular update loops and then called the cleanUp() method at the end of each update loop, like this:

	
function cleanUp()
{
	var aCleanup = [];
	cars.forEachDead(function(item){
		aCleanup.push(item);
	});
	
	var i = aCleanup.length - 1;
	while(i > -1)
	{
		var getitem = aCleanup[i];
		getitem.destroy();
		i--;
	}
}

Here I iterate through all the cars I’ve set as dead in regular update functions, save them into cleanup array and then go through it and call destroy() method on every car set to be removed, without getting any errors.