Spatial partitioning is essential for performance in games with many entities. This example shows how to use a voxel grid to efficiently query nearby entities without checking every entity in the world.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/Ukendio/jecs/llms.txt
Use this file to discover all available pages before exploring further.
Overview
The spatial grid pattern divides the world into fixed-size cells (voxels). Entities are assigned to voxels based on their position, and queries only check entities in relevant voxels.Benefits
- Performance: Only check entities in nearby voxels instead of the entire world
- Scalability: Handles thousands of entities efficiently
- Flexibility: Works for perception, collision detection, area queries, etc.
Complete Example
This example implements a perception system where a player can detect enemies within range and field of view.Breaking It Down
Grid Setup
map table stores voxel entities indexed by their grid position. The grid constant defines the size of each voxel cell.
Adding Entities to Voxels
The
ChildOf relationship is used to associate entities with their voxel. This allows efficient queries like world:query(Position, pair(ChildOf, voxel_id)) to find all entities in a specific voxel.Updating Entity Positions
Spatial Query
Performance Characteristics
Without Spatial Grid
- Query all entities in world: O(n)
- For 10,000 entities, check all 10,000
With Spatial Grid
- Query entities in voxel: O(n/v) where v is number of voxels
- For 10,000 entities across 100 voxels, check only ~100 entities
Expanding to Multi-Voxel Queries
For larger perception ranges, query multiple voxels:Key Patterns
Using ChildOf for Spatial Relationships
Lazy Voxel Creation
Use Cases
Collision Detection
Only check collisions between entities in nearby voxels
AI Perception
NPCs search for targets only in their local area
Area Queries
Find all entities in a region (explosions, spells, etc.)
Network Relevancy
Only replicate nearby entities to clients
Next Steps
Basic Usage
Learn the fundamentals of jecs
Networking
Replicate entities across client and server