Newbie having some confusion with Matter Physics

Hi all, I’m really new to programming and Phaser, so please bear with me.

I’m trying to create a pretty simple game where bullets are shot at balls and once they collide, both the bullet and the ball is destroyed. I’m having an issue where the destroy() function removes the physics boundary, but not the image. See the attached image for what I mean. Annotation 2020-05-04 125039

Here is the code for the collision:

this.matter.world.on(
  "collisionstart",
  (e, bodyA, bodyB) => {
    if (bodyA.isStatic || bodyB.isStatic) {
      console.log(bodyA);
    } else {
      bodyA.destroy();
      bodyB.destroy();
      this.scene.pause();
    }
  },
  this
);

And below is the code for how both the bodys are created

this.balls = [];
let x = 0;
for (let i = 40; i < 400; i += 40) {
  this.balls[x] = this.matter.add.image(i, 20, "ball1");
  this.balls[x].setCollisionCategory(this.ballCategory);
  this.balls[x].setCircle(45);
  this.balls[x].setScale(0.3);
  this.balls[x].setBounce(0.5);
  x++;
}

this.bullet = this.matter.add.image(
  this.player.x,
  this.player.y - 50,
  "ball1"
);

let speed = 10;
let angle = Phaser.Math.Angle.BetweenPoints(this.player, e);
this.bullet.setScale(0.1);
this.bullet.setCircle(5);
this.bullet.setVelocityX(Math.cos(angle) * speed);
this.bullet.setVelocityY(Math.sin(angle) * speed);

Any help with this would be appreciated.

Thanks!

Game objects and physics bodies are two separate entities. The collisionstart event receives the body. Your handler destroys it but keeps the game object intact. Instead of bodyA.destroy(), use bodyA.gameObject.destroy() (likewise for bodyB). Destroying an entire game object will also destroy its body.

1 Like

That worked! Thank you!

1 Like