12

As already mentioned in the title, I am looking for a way, to disable every collision of a body in Matter.js. It should still be linkable with Constraints, and there should be the possibility of enabling the collision again after some time. Is there a way to do this? The hard thing about it, is that the object should not collide with any other object, but all the other objects should collide with each other.

d0n.key
  • 1,318
  • 2
  • 18
  • 39

2 Answers2

8

You can use collision filters, like so:

const body = Matter.Bodies.rectangle(100, 100, 50, 50);
// turns off collisions
body.collisionFilter = {
  'group': -1,
  'category': 2,
  'mask': 0,
};

From the docs:

If the two bodies have the same non-zero value of collisionFilter.group, they will always collide if the value is positive, and they will never collide if the value is negative.

Using the category/mask rules, two bodies A and B collide if each includes the other's category in its mask, i.e. (categoryA & maskB) !== 0 and (categoryB & maskA) !== 0 are both true.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Jatin Mathur
  • 89
  • 1
  • 3
  • Just a quick optimisation: That last comma after "'mask': 0" is not needed – Yaume Jun 29 '21 at 07:33
  • 8
    @Yaume I see no problem with trailing commas in object definitions. Some languages (Go) even _require_ it. It makes it easy to add new pairs and change the order of pairs without syntax (or worse yet, logical) errors. It's certainly not an optimization from a performance standpoint (or readability, for that matter)... – ggorlen Dec 08 '21 at 20:33
  • 1
    @Yaume this is extremely nitty and boils down to personal preference – Adam Fratino Aug 24 '22 at 03:09
5

see

Matter.IBodyDefinition.isSensor

in order to disable physical collisions for the Body. The Body can still be used as a sensor for collisions.

gaitat
  • 12,449
  • 4
  • 52
  • 76
Christopher Stock
  • 1,399
  • 15
  • 18