Visualize Broadphase Spatial Partitions in Matter.js

This article explains how to visualize broad-phase spatial partition cells in Matter.js using the built-in showBroadphase debug rendering option. You will learn the mechanics behind Matter.js broad-phase collision detection, the exact syntax required to enable grid cell visualization in the native renderer, and practical debugging tips to diagnose spatial partitioning and performance issues in your physics simulations.

What is Broadphase Collision Detection?

Before performing exact, resource-intensive polygon intersection tests (narrow-phase), Matter.js performs a broad-phase check. The engine uses spatial partitioning (typically via bounding boxes and a spatial hash grid) to group bodies into coarse cells. Only objects sharing the same or neighboring cells are flagged as potential collision pairs.

Visualizing this grid helps developers analyze how bodies are distributed across cells, verify that spatial partition boundaries update correctly, and diagnose performance bottlenecks caused by excessive bodies crowding a single partition.

Enabling showBroadphase in the Renderer

Matter.js provides a built-in canvas renderer (Matter.Render) with multiple debugging flags. The showBroadphase option renders the boundaries of the internal spatial partition buckets onto the canvas.

1. Enabling at Initialization

You can enable broad-phase visualization when instantiating the renderer by setting showBroadphase: true inside the options object:

const { Engine, Render, Runner, Bodies, Composite } = Matter;

// Create engine
const engine = Engine.create();

// Create renderer with showBroadphase enabled
const render = Render.create({
  element: document.body,
  engine: engine,
  options: {
    width: 800,
    height: 600,
    wireframes: true, // Recommended for clear debug visuals
    showBroadphase: true
  }
});

// Run the renderer and engine
Render.run(render);
const runner = Runner.create();
Runner.run(runner, engine);

2. Toggling Dynamically at Runtime

If your simulation is already running, you can toggle broad-phase visualization dynamically without recreating the renderer:

// Enable broadphase visualization
render.options.showBroadphase = true;

// Disable broadphase visualization
render.options.showBroadphase = false;

This approach is particularly useful for mapping debug states to keyboard shortcuts or UI controls.

Understanding the Visual Output

When showBroadphase is active, Matter.js draws lines representing the bounding regions and partition buckets managed by the broad-phase controller:

Technical Considerations