7
votes

I am trying to detect when two object collide with each other, but I am not sure how to do it.

I have the following scene, which adds two physics images to the scene. I just need a way to detect when the two collide.

export class MainGame extends Scene {
  public create() {
    // Create the player
    this.player = this.matter.add.image(300, 100, 'player')

    // Create a pillar
    let pillar = this.matter.add.image(500, 0, 'pillar1', null, { isStatic: true })

    // Somehow detect collision between the two...
  }
}

What I cannot figure out is how to detect when the player collides with the pillar. Everything I have searched for is how to do this using arcade physics, but I am using matter physics.

I cannot find any information on how to detect collision and then run a function.

2

2 Answers

9
votes

After looking at examples here, To call a function on collision, use the 'oncollisionStart' event like in this example.

this.matter.world.on('collisionstart', function (event, bodyA, bodyB) {
    console.log('collision');
});
0
votes

Another way to do this is to add the collision event callback to the object itself.

var paddle = this.matter.add.image(400, 550, 'assets', 'paddle.png');
var paddle.setOnCollide(pair => {
  // pair.bodyA
  // pair.bodyB
});

See the documentation under enableCollisionEventsPlugin(): https://photonstorm.github.io/phaser3-docs/Phaser.Physics.Matter.MatterPhysics.html and also what a pair looks like: https://brm.io/matter-js/docs/files/src_collision_Pair.js.html#

You can also listen for specific collisions.

var paddle.setOnCollideWith(ball, pair => {
  // Do something
});