SpatialHashGrid

2D Spatial Hash Grid broadphase partitioning space into uniform buckets. Supports efficient range queries, AABB queries, teleportation, dynamic updates, and robust handling of negative coordinates and oversized colliders.

Constructor

new SpatialHashGrid(configopt)

Parameters:
NameTypeAttributesDescription
configObject<optional>
Properties
NameTypeAttributesDefaultDescription
cellSizenumber<optional>
64

Width and height of each spatial cell

maxCellSpannumber<optional>
32

Maximum cells an oversized object can span across one dimension

Classes

SpatialHashGrid

Members

size

Get the count of tracked entries.

Methods

clear()

Clear all cells and entries (e.g. on scene unload).

getCellKeysForBounds(bounds) → {Set.<string>}

Compute set of cell keys covered by an AABB. Handles negative cells and clamps huge colliders to maxCellSpan.

Parameters:
NameTypeDescription
boundsObject

{ left, right, top, bottom }

Returns:
Type: 
Set.<string>

getPotentialCollisionPairs() → {Array.<Array>}

Generate unique potential collision pairs across all cells. Returns an array of [entryA, entryB] pairs with deterministic ordering.

Returns:
Type: 
Array.<Array>

insert(entry, bounds)

Insert an entry into the spatial grid.

Parameters:
NameTypeDescription
entryObject

Object identifier (collider, entity, etc.)

boundsObject

{ left, right, top, bottom }

queryAABB(bounds) → {Array.<Object>}

Query all unique entries whose bounding box overlaps the given AABB.

Parameters:
NameTypeDescription
boundsObject

{ left, right, top, bottom }

Returns:
Type: 
Array.<Object>

queryRadius(x, y, radius) → {Array.<Object>}

Query all unique entries within a circular radius of a point.

Parameters:
NameTypeDescription
xnumber

Center X

ynumber

Center Y

radiusnumber

Search radius

Returns:
Type: 
Array.<Object>

remove(entry) → {boolean}

Remove an entry from all cells.

Parameters:
NameTypeDescription
entryObject
Returns:

Whether entry was present and removed

Type: 
boolean

teleport(entry, newBounds)

Teleport an entry instantly to new bounds.

Parameters:
NameTypeDescription
entryObject
newBoundsObject

update(entry, newBounds) → {boolean}

Update an entry's position and bounding box. If the cell coverage did not change, avoids bucket re-insertions.

Parameters:
NameTypeDescription
entryObject
newBoundsObject
Returns:

Whether spatial bucket assignment changed

Type: 
boolean

worldToCell(coord) → {number}

Convert world coordinate to cell coordinate index. Uses Math.floor to correctly handle negative coordinates.

Parameters:
NameTypeDescription
coordnumber
Returns:
Type: 
number