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:

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