.destroy() method usage

Hey ya’ll, total newb to phaser here so go easy on me. I am trying to remove sprites and I can’t seem to get it to work. my code is all still very simple and small scale rn so I assume it’s just me using something incorrectly…

let game = new Phaser.Game(config);
let cowGroup;
let cows = 0;
let gameOver = false;

function preload() {
  this.load.image('water', 'assets/water.png');
  this.load.image('grass', 'assets/grass.png');
  this.load.image('thick_grass', 'assets/thick_grass.png');
  this.load.spritesheet('cow', 'assets/1cow.png', {
    frameWidth: 32,
    frameHeight: 32,
  });
}

function create() {
  for (let i = 0; i < map.length; i++) {
    for (let j = 0; j < map[i].length; j++) {
      let image = this.add.image(i * 8, j * 8, map[i][j]);
      image.setOrigin(0, 0);
    }
  }
  this.physics.world.gravity.y = 0;
  this.physics.world.setBounds(0, 0, 800, 600);
  cowGroup = this.physics.add.group();
  //just creating two test cows here…
  createCow(`${cows++}`, 100, 100);
  createCow(`${cows++}`, 200, 200);
}

function createCow(id, x, y) {
  const cow = cowGroup.create(x, y, 'cow');

  cow.setCollideWorldBounds(true);
  cow.cowId = id;
  cow.food = 10;
}

function killCow(id) {
  const cowToKill = cowGroup.getFirst(function (cow) {
    return cow.cowId === id;
  }, this);
  if (cowToKill) {
    //as you can see here i am calling .destroy() but i've also tried to use .disableBody() and .remove() on the cow group
    console.log(`killing cow with id: ${id}`);
    cowToKill.destroy(true);
    cowGroup.remove(cowToKill, true);
    console.log(`killed cow with id: ${id}`);
  }
}

function update() {
  if (gameOver) {
    return;
  }

  cowGroup.children.iterate(function (cow) {
    cow.food--;
    if (cow.food <= 0) {
      killCow(cow.cowId);
    }
  });
  if (cowGroup.countActive(true) === 0) {
    gameOver = true;
    console.log('Game Over!');
  }
}

I know this is probably just me being a total noob and not knowing how to do things but any help would be greatly appreciated.

:wave:

You’re using destroy() correctly but not getFirst(), which is creating a new cow each time. :slight_smile:

You could search the group with

const [cowToKill] = cowGroup.getMatching('cowId', id);

If you use destroy() on a group member then the group will remove it automatically, so you don’t have to call remove() also.

1 Like

Thanks a ton, that fixed it! I appreciate it a lot :fist_right: