Iterate sprites in group and remove a selection of certain enemy sprites?

I’m working on a snake-type game where the player can eat apples and has to avoid walls. I’ve put all the game object in a Phaser.group and during the game it will typically contain something like this:

_grpObject.list
0. sprite frame "appl" (data obj_type = 1)
1. sprite frame "wall" (data obj_type = 99)
2. sprite frame "gate" (data obj_type = 50) (first gate)
3. sprite frame "gate" (data obj_type = 50) (second gate)
4. sprite frame "wall" (data obj_type = 99)
etc.

When the player grabs a key item it should unlock all gates, i.e. remove all gate items from the group.
So I’ve tried this code:

// remove all GATE sprites from group
this._grpObject.iterate(function (spr) {
	if (spr.data.get("obj_type") == 50) {
		this._grpObject.remove(spr);
	};
}.bind(this));

However, the result is that not all “gate” sprites are removed, there still are some left. The example result will look like this:

_grpObject.list
0. sprite frame "appl" (data obj_type = 1)
1. sprite frame "wall" (data obj_type = 99)
2. sprite frame "gate" (data obj_type = 50) (second gate)
3. sprite frame "wall" (data obj_type = 99)
etc.

This is an example, but in a larger list of items every other gate is removed, so when there are consecutive “gate” sprites it will remove one, then skip one, remove one etc.

I understand that the cause of this, is that it is iterating over the indexes of the items and removing items will change the indexes. However, I don’t know what is the best way do this.

So, what is the best way to iterate over all sprites in a group and remove only certain sprites?

Iterate backwards.

2 Likes

Sometimes the solution is so simple :smiley: LOL

I’ve changed my code to this and that works:

// remove all GATE sprites from group
for (var i = this._grpObject.list.length-1; i >= 0; i--) {
	var spr = this._grpObject.list[i];
	if (spr.data.get("obj_type") == 50) {
		this._grpObject.remove(spr);
	};
};

:slight_smile:

Btw, I was writing some keyboard handling, and read this, which addresses the AZERTY question I seem to recall you had…

@Milton I saw your link and I don’t quite understand the differences betwen code, key, keyCode properties in JavaScript, but anyway I have just replied here.