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:
bucketWidth: A number specifying the horizontal width of each grid cell in world units (typically pixels). The default value is48.bucketHeight: A number specifying the vertical height of each grid cell in world units. The default value is48.
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:
- Start Column:
Math.floor(body.bounds.min.x / grid.bucketWidth) - End Column:
Math.floor(body.bounds.max.x / grid.bucketWidth) - Start Row:
Math.floor(body.bounds.min.y / grid.bucketHeight) - End Row:
Math.floor(body.bounds.max.y / grid.bucketHeight)
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:
- Buckets set too small: If the bucket dimensions are significantly smaller than the bodies, individual bodies will overlap many buckets simultaneously. This creates excessive memory allocation, duplicate pair checks, and hash lookups.
- Buckets set too large: If the buckets are too large relative to the bodies, too many bodies will occupy the same bucket. This degrades the broad-phase efficiency, forcing the engine closer to \(O(n^2)\) computational complexity during the narrow phase.
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.