Matter.js Collision Group Property Explained

In Matter.js, the collisionFilter.group property is a streamlined mechanism used to dictate whether specific rigid bodies should always or never collide with each other. This article provides a focused explanation of how the collision group property works, how its numerical values alter collision detection, how it interacts with standard collision masks, and practical scenarios where it is best applied in 2D physics simulations.

How Collision Groups Work

Every body in Matter.js contains a collisionFilter object, which includes a group property represented as an integer. By default, this value is set to 0.

The group property acts as a priority override over the standard bitmask properties (category and mask). When two bodies interact, the physics engine checks their group values first before calculating any bitmask logic:

  1. Same Positive Value (group > 0): If two bodies share the same positive integer (for example, both have group: 1), they will always collide, regardless of what is configured in their category or mask properties.
  2. Same Negative Value (group < 0): If two bodies share the same negative integer (for example, both have group: -1), they will never collide, completely ignoring their category and mask settings.
  3. Different Values or Zero (group: 0): If the two bodies have different group values, or if either body has a group value of 0, the group rule is bypassed. The engine then falls back to evaluating collisions using the category and mask bitwise rules.

Implementation Example

To apply a collision group, define the group property inside the collisionFilter configuration during body creation:

// Two bodies that will never collide with each other
const limbA = Matter.Bodies.rectangle(100, 200, 50, 50, {
  collisionFilter: {
    group: -1
  }
});

const limbB = Matter.Bodies.rectangle(120, 200, 50, 50, {
  collisionFilter: {
    group: -1
  }
});

In this setup, limbA and limbB pass through one another freely because they share a matching negative group value.

Common Use Cases