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:

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