Using Negative Collision Groups in Matter.js
This article explains how to use negative collision groups in Matter.js to prevent specific bodies from colliding with each other. By assigning bodies matching negative integer values in their collision filters, you can ensure they pass through one another while maintaining normal collision behaviors with the rest of the physics world.
How Collision Groups Work in Matter.js
Matter.js controls body collisions using the
collisionFilter property. Inside this filter, the
group property accepts an integer that directly dictates
whether two bodies should interact, overriding the default
category and mask bitmask rules:
- Positive group (
group > 0): Bodies with the same positive group value will always collide. - Negative group (
group < 0): Bodies with the same negative group value will never collide. - Default group (
group === 0): The engine ignores the group rule and falls back to standardcategoryandmaskchecks.
Implementing Negative Collision Groups
To prevent two or more bodies from colliding, assign them the exact
same negative integer in their collisionFilter.group
setting.
Code Example
const { Engine, Render, Runner, Bodies, Composite } = Matter;
const engine = Engine.create();
const world = engine.world;
// Define a shared negative group index
const GHOST_GROUP = -1;
// Create two bodies that should not collide with each other
const bodyA = Bodies.circle(200, 100, 30, {
collisionFilter: {
group: GHOST_GROUP
}
});
const bodyB = Bodies.rectangle(200, 300, 100, 40, {
isStatic: true,
collisionFilter: {
group: GHOST_GROUP
}
});
// Create a third body that has the default group (0)
const ground = Bodies.rectangle(200, 500, 400, 20, {
isStatic: true
});
Composite.add(world, [bodyA, bodyB, ground]);In this example, bodyA will pass directly through
bodyB because both share the group value -1.
However, because ground uses the default group
0, bodyA will still collide with
ground as long as their category and mask settings permit
it.
Key Considerations
- Different Negative Values Still Collide: If Body A
has a group of
-1and Body B has a group of-2, they will not ignore each other based on the group rule. Instead, the engine will fall back to evaluating theircategoryandmaskproperties. - Efficiency: Using negative groups is the fastest and simplest way to disable collisions between a dedicated set of objects (such as members of the same team or multi-part ragdoll limbs) without having to calculate bitwise category masks.