简体   繁体   中英

Phaser 3: Matter physics detect collision

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.

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');
});

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM