---
url: /pawn/docs/guide/space.md
description: >-
  Finding entities near a point (SpatialIndex) and mapping board cells to world
  points with Grid.
---

# Grids and spatial queries

Two helpers for where things are on the ground: finding the entities
within reach of a point, and turning the cells of a board into world
points and back. Distances are measured between
[world positions](./hierarchy.md#world-position), so `ChildOf` children
count where they are drawn.

## Entities near a point

`SpatialIndex` finds the entities with a trait whose world position is
within `radius` of a world-space point, nearest first, e.g. the enemies a
tower reaches or the vehicles near a stop. It keeps a hash grid, so it
stays fast for thousands of entities and many queries a frame:

```ts
import { SpatialIndex } from "@pawnjs/core";

engine.use(new SpatialIndex({ cellSize: 2 })); // optional; plugin() installs one
const [target] = engine.plugin(SpatialIndex).near(tower, 2.5, Enemy);
```

* The grid of a trait is built on its first query in a frame and reused
  by the frame's later queries, so positions are as of that first query.
  Entities that get or lose the trait count at once.
* `cellSize` (2 by default) works best close to the usual query radius.
  A radius much wider than a cell checks every entity.
* With 100,000 entities and 100 queries a frame, `near` takes about 33 ms
  where checking every entity takes about 1.2 s (`bun run bench` in
  `packages/core`, headless).

## Grids

`Grid` maps the cells of a board on the ground (the xz plane) to world
points and back, such as the tiles of a game or the slots of a warehouse.
Columns run along x, rows along z, and the grid is centered on `center`:

```ts
import { Grid } from "@pawnjs/core";

const grid = new Grid({ columns: 12, rows: 8, size: 1 });
tower.set(Position, grid.toWorld(3, 2, 0.5)); // middle of the cell, y 0.5
grid.fromWorld(hit.point); // { column, row }, or undefined off the grid
grid.contains(12, 0); // false
grid.line([{ column: 0, row: 1 }, { column: 3, row: 1 }]); // 4 cells
for (const { column, row } of grid.cells()) spawnTile(column, row);
```

`line(corners)` lists the cells along straight lines (across, down or
diagonal) through corner cells, such as a road; `key(column, row)` gives
`"column,row"` for maps and sets. A `Grid` is plain math and spawns
nothing.
