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?