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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

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