How to Use Matter.js Positive Collision Groups
Matter.js provides a robust collision filtering system to control
which rigid bodies interact during a simulation. By utilizing the
collisionFilter.group property with positive integers, you
can explicitly force designated bodies to always collide with one
another, completely bypassing the default category and mask rules. This
article explains how the collision grouping mechanism works in Matter.js
and provides the code needed to enforce collisions between specific
physics bodies.
Understanding Collision Groups in Matter.js
Every rigid body in Matter.js possesses a
collisionFilter object with three main properties:
group, category, and mask. Among
these, the group property holds the highest priority in
determining whether a collision occurs:
- Group 0 (Default): The engine ignores the group and
evaluates interaction using
categoryandmaskbitmasks. - Negative Group (
group < 0): Bodies sharing the same negative integer will never collide, regardless of their categories or masks. - Positive Group (
group > 0): Bodies sharing the exact same positive integer will always collide, overriding any rules defined bycategoryandmask.
Implementing Positive Collision Groups
To force two or more bodies to collide, assign them the identical
positive integer inside their collisionFilter.group
configuration during creation, or modify the property directly on
existing bodies.
const { Engine, Render, Runner, Bodies, Composite } = Matter;
// Create an engine
const engine = Engine.create();
// Define a shared positive group identifier
const FORCED_COLLISION_GROUP = 1;
// Create body A
const bodyA = Bodies.circle(200, 100, 30, {
collisionFilter: {
group: FORCED_COLLISION_GROUP,
category: 0x0001,
mask: 0x0000 // Normally would not collide with anything
}
});
// Create body B
const bodyB = Bodies.rectangle(200, 300, 100, 40, {
isStatic: true,
collisionFilter: {
group: FORCED_COLLISION_GROUP,
category: 0x0002,
mask: 0x0000 // Normally would not collide with anything
}
});
// Add bodies to the world
Composite.add(engine.world, [bodyA, bodyB]);Key Rules and Considerations
- Exact Value Matching: The collision override only
applies when bodies share the exact same positive integer. A
body with
group: 1and a body withgroup: 2will fall back to their defaultcategoryandmasklogic to determine if they interact. - Overriding Zero Masks: Even if a body has its
maskset to0x0000(which typically disables all collisions for that object), matching positive group values will still force the physics engine to register contact and compute collision responses. - Dynamic Updating: Collision filters are mutable at
runtime. You can alter a body's group dynamically by assigning
body.collisionFilter.group = 1;when a specific game event occurs, instantly forcing it to interact with other bodies in group 1.