How to tell if two bodies are touching with matter.js
Asked Answered
I

4

6

I'm using matter.js as a physics engine, and I see that I can detect collisions.

However, I cannot figure out how to tell if two bodies are in contact with one another after a collision occurs. Is there any way to do this?

(In my particular case, I want a ball to jump only if it's touching a particular piece of ground.)

Indifference answered 4/1, 2018 at 5:46 Comment(1)
I use Events.on(this.engine, 'collisionActive', function (event) { }); to handle library's collision event. Use event.pairs to get two bodies and check id attribute to determine specific bodies. Here's an example.Corin
F
7

This is a very late answer and I know you already accepted an answer, but I just found this really easy solution. Matter.js has a module called SAT which detects collisions with Separating Axis Theorem. It's single method can be used to detect if two objects are colliding:

Matter.SAT.collides(playerObject, groundObject).collided // returns either true or false depending on if the two objects are colliding 
Floating answered 30/1, 2021 at 18:3 Comment(3)
I believe this was in a comment under Imesh’s answer, but this does seem correct. Thank you for making it an answer!Indifference
This has been deprecated and replaced by Matter.Collision.collides(a, b) != nullPleuron
From the docs for SAT: "This class is deprecated. This module has now been replaced by Matter.Collision. All usage should be migrated to Matter.Collision. For back-compatibility purposes this module will remain for a short term and then later removed in a future release." Use Matter.Collision.collides(bodyA, bodyB, [pairs]) → Collision | Null as described in this answer elsewhere in this thread.Demetria
M
3

Use Matter.Collision.collides and check if it's null.

if (Matter.Collision.collides(a, b) != null) {
    // collision happened
}
Misapprehend answered 26/1, 2022 at 8:10 Comment(0)
I
1

Use sensors.

The object detection between the objects themselves is not very good at all, so put a sensor on at least one of the things you want to detect collisions for. Either actually attach it rigidly to your body or find some way to update it so it always moves to the position of the body you want to track and do your collision detection like that.

Indifference answered 16/1, 2018 at 6:25 Comment(0)
E
0

I think they have in-built collision detection api.

reference documentation

Matter.Detector.canCollide(filterA, filterB)

This method returns a bool saying whether it's in collision or not.

Esdras answered 4/1, 2018 at 5:53 Comment(1)
That only detects whether the collisionFilter of two bodies WOULD collide, IE, if the masks and categories match (like 0b0010 & 0b0111 == true, per their collisionFilter property). If they wanted to detect collision manually, do: var collision = Matter.SAT.collides(bodyA, bodyB); if (collision.collided) { // do something }Tyre

© 2022 - 2024 — McMap. All rights reserved.