Matter.js Grid Bucket Size Parameters

This article explains how the broad-phase collision detection system in Matter.js utilizes spatial hashing through Matter.Grid. It outlines the specific parameters—bucketWidth and bucketHeight—that define bucket dimensions, explains how they operate within the physics engine, and provides guidance on tuning them for optimal collision detection performance.

The Core Bucket Size Parameters

In the Matter.Grid module, the dimensions of the spatial grid cells are controlled directly by two properties:

These properties are passed into the Grid.create() factory method upon instantiation:

const grid = Matter.Grid.create({
  bucketWidth: 64,
  bucketHeight: 64
});

How Matter.Grid Uses Bucket Dimensions

The broad-phase collision detection phase reduces computational overhead by narrowing down which pairs of bodies might be colliding before expensive narrow-phase checks occur.

Matter.Grid implements a spatial hash grid. During an update cycle, the engine calculates the axis-aligned bounding box (AABB) of each active body. The coordinates of these bounds are divided by bucketWidth and bucketHeight using Math.floor to determine the range of grid coordinates (columns and rows) the body overlaps:

The body is then inserted into bucket keys representing these coordinate intersections (e.g., C0R0, C1R0). Only bodies that share at least one bucket are evaluated for collisions in subsequent phases.

Performance Considerations When Tuning Bucket Size

Setting appropriate values for bucketWidth and bucketHeight depends on the average size and density of the bodies in the simulation:

As a general rule, set bucketWidth and bucketHeight roughly equal to 1.5 to 2 times the average diameter of the objects in your simulation.