Correct Way to Obtain Collided Sprite

Hi,

What is the correct way to detect which sprite from a group collides

In my game I have a sprite group containing over 20 sprites. I have an overlap which has a call back function to deal with the player “killing” the enemy sprite.

this.physics.add.overlap(this.wormgroup, this.player, this.hitPlayer,null,this)

The callback filters the group for the sprite I want to kill off by the overlapX attribute. This works if the player attacks from the right and the sprite is moving towards, but not if they are attacking from the left and the sprite is moving away.

Also, isn’t this going to pick up overlaps between other sprite groups as I will have several at once which could cross paths?

if(this.playerAttack) {
  var worms = this.wormgroup.children.entries.filter(child => child.body.overlapX > 0 );
  worms.forEach(worm => this.deadworms.create(worm.x, worm.y, 'worm'));
  worms.forEach(worm => worm.destroy());
  this.deadworms.playAnimation('wormmove');
  this.deadworms.setVelocity(0,-400);
}

I’ve been playing around with different things and looking online for hours, but can’t find a definitive answer to this. Are you meant to attach a callback function to the specific sprite? If so how?

The colliding sprite is in the callback arguments. I think you want something like

this.physics.add.overlap(
  this.player,
  this.wormgroup,
  function (player, worm) {
    if (worm.body.overlapX > 0) worm.destroy();
    // …
  },
  null,
  this
);
1 Like

Thanks again! I’ve got that to work now. :smiley:

1 Like