Spatial Index API
createGridSpatialIndex
Section titled “createGridSpatialIndex”function createGridSpatialIndex<T>(cellSize?: number): GridSpatialIndex<T>Creates a uniform grid-based spatial index.
Parameters:
cellSize- Grid cell size (default 100)
Choosing cellSize:
- Too small: High memory usage, reduced query efficiency
- Too large: Too many objects per cell, slow iteration
- Recommended: 1-2x average object spacing
Management Methods
Section titled “Management Methods”insert
Section titled “insert”Insert an object into the index:
spatialIndex.insert(enemy, { x: 100, y: 200 });remove
Section titled “remove”Remove an object:
spatialIndex.remove(enemy);update
Section titled “update”Update object position:
spatialIndex.update(enemy, { x: 150, y: 250 });Clear the index:
spatialIndex.clear();Query Methods
Section titled “Query Methods”findInRadius
Section titled “findInRadius”Find all objects within a circular area:
// Find all enemies within radius 50 of point (100, 200)const enemies = spatialIndex.findInRadius( { x: 100, y: 200 }, 50, (entity) => entity.type === 'enemy' // Optional filter);findInRect
Section titled “findInRect”Find all objects within a rectangular area:
import { createBounds } from '@esengine/spatial';
const bounds = createBounds(0, 0, 200, 200);const entities = spatialIndex.findInRect(bounds);findNearest
Section titled “findNearest”Find the nearest object:
// Find nearest enemy (max search distance 500)const nearest = spatialIndex.findNearest( playerPosition, 500, // maxDistance (entity) => entity.type === 'enemy');
if (nearest) { attackTarget(nearest);}findKNearest
Section titled “findKNearest”Find the K nearest objects:
// Find 5 nearest enemiesconst nearestEnemies = spatialIndex.findKNearest( playerPosition, 5, // k 500, // maxDistance (entity) => entity.type === 'enemy');raycast
Section titled “raycast”Raycast (returns all hits):
const hits = spatialIndex.raycast( origin, // Ray origin direction, // Ray direction (should be normalized) maxDistance, // Maximum detection distance filter // Optional filter);
// hits are sorted by distancefor (const hit of hits) { console.log(`Hit ${hit.target} at ${hit.point}, distance ${hit.distance}`);}raycastFirst
Section titled “raycastFirst”Raycast (returns only the first hit):
const hit = spatialIndex.raycastFirst(origin, direction, 1000);if (hit) { dealDamage(hit.target, calculateDamage(hit.distance));}Properties
Section titled “Properties”// Get number of objects in indexconsole.log(spatialIndex.count);
// Get all objectsconst all = spatialIndex.getAll();Blueprint Nodes
Section titled “Blueprint Nodes”FindInRadius- Find objects within radiusFindInRect- Find objects within rectangleFindNearest- Find nearest objectFindKNearest- Find K nearest objectsRaycast- Raycast (all hits)RaycastFirst- Raycast (first hit only)