albator2018
albator2018

Reputation: 91

How to remove only one sprite of a group of sprites in a game?

I am coding a game with #PhaserJS and I want to delete only one sprite in a group of sprites everytime the player is touched by the AI sprites which decrements the number of lifes by one, so in the create function i have

  lifes = game.add.group();
  for(i = 0; i < 3; i++){
    j = i + 1;
    life = game.add.sprite(20 * j, 20, 'life');

    lifes.add(life);
  }
  lifes.fixedToCamera = true;

Then in the update function I just try to remove one sprite when it collides

function hitNinja (ninja, ronins) {
  lifes.kill();
}

The problem is that it supress all the group of sprites that is displayed at the top of the screen like in the image bellow

Life x 3

enter image description here

Upvotes: 2

Views: 2727

Answers (1)

Kamen Minkov
Kamen Minkov

Reputation: 3722

In your example lifes is the whole group, so calling kill() on it will destroy it along with everything it's in it. If you want to act upon individual elements of the group, you should iterate over them in some way.

function hitNinja (ninja, ronins) {
    var children = lifes.getAll();
    children[children.length - 1].kill();
}

Keep in mind that kill() is a method you'd use if you want to 'revive' the sprite later on; otherwise, destroy() might be the saner choice.

Reference for Phaser.Group.

Upvotes: 3

Related Questions