Jump to content

Phaser 3 Matter. Collision events for specific objects


Rodion
 Share

Recommended Posts

Hello, I'm using Phaser 3 and the physics engine matter. I need to call a function when one object collides with a particular object.

For example I have a tank, barrels, hearts. Then there will be bullets, other tanks, some other objects. You need to call the function when the tank collides with the barrel, it should explode, and if it collides with the heart, it will replenish life.

this.matter.world.on('collisionstart', function (event) {
    bangBarrel();
});

this method calls the function in any collision. How to trigger the function when the tank collide with the barrel, and how to trigger the function when the tank collide with the heart?

Link to comment
Share on other sites

I found one example, everything works, but is it right to do so?

example collision in matter

this.matter.world.on('collisionstart', function (event) {
        for (var i = 0; i < event.pairs.length; i++) {
            var bodyA = getRootBody(event.pairs[i].bodyA);
            var bodyB = getRootBody(event.pairs[i].bodyB);

            if ((bodyA.label === 'barrel' && bodyB.label === 'tank') || (bodyB.label === 'barrel' && bodyA.label === 'tank')) {
                bangBarrel();
            }
        }
    }, this);

function getRootBody(body) {
    if (body.parent === body) {
        return body;
    }
    while (body.parent !== body) {
        body = body.parent;
    }
    return body;
}

 

Link to comment
Share on other sites

  • 1 year later...
  • 1 month later...

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

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...