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:
- Same Positive Value (
group > 0): If two bodies share the same positive integer (for example, both havegroup: 1), they will always collide, regardless of what is configured in theircategoryormaskproperties. - Same Negative Value (
group < 0): If two bodies share the same negative integer (for example, both havegroup: -1), they will never collide, completely ignoring theircategoryandmasksettings. - Different Values or Zero (
group: 0): If the two bodies have different group values, or if either body has a group value of0, the group rule is bypassed. The engine then falls back to evaluating collisions using thecategoryandmaskbitwise 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
- Composite Objects and Ragdolls: When building multi-part bodies connected by constraints (such as a character's torso and limbs), assigning all parts the same negative group prevents limbs from unnaturally colliding and glitching against each other while still allowing them to collide with the environment.
- Team-Based Mechanics: In multiplayer or action games, projectiles fired by a character can share a negative group with the character's body parts to prevent self-damage or accidental obstruction upon firing.
- Forced Collision Layers: Positive groups guarantee that critical elements (like game-ending hazards and the player) will always trigger collision responses without requiring complex layer-mask configurations.