grid() function

Available since @irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room host

The grid() function makes interest by grid cell: each entity gets the key of the cell it’s in, and each connection subscribes to the cells around it, so it sees the entities near it.

Syntax

grid(options)

Parameters

options

An object with these properties:

cellSize
The size of a cell, in world units.
dims
The axes: "xy", "xz" or "xyz".
around(room, connection)
The entity or point [x, y, z?] a connection sees around, or undefined, in which case it subscribes only to EVERYWHERE.
range
A distance in world units. A connection sees exactly the entities within it of around: a circle on "xy" and "xz", a sphere on "xyz". Give range or radius, not both.
radius
A whole number of cells. A connection sees every entity in the square, or cube, of cells within radius cells of its own on each axis.
position(room, entity) Optional
An entity’s point [x, y, z?], or undefined for none. Defaults to its x, y and z fields. It places an entity around returns too.
prefix Optional
A string that starts every key the grid gives, EVERYWHERE included, so two grids’ keys never meet.
kinds Optional
The kinds the grid places. Other kinds get no key from it, and its sees lets them through.

Return value

An interest part with keysOf, subscriptionsOf and, with range, sees: an Interest as it is, or a part to join with combine().

Exceptions

TypeError
Thrown if options has both range and radius, or neither.
RangeError
Thrown for a range that isn’t a finite number from 0, or a radius that isn’t a whole number from 0.

Description

An entity’s key is cellKey() of its cell, where a cell coordinate is Math.floor(position / cellSize). Entities with no position on the grid’s axes get the key EVERYWHERE ("*"), which every connection subscribes to.

Examples

Seeing ships within 500 units

// sea.ts
import { defineRoom, defineSchema, entity, grid } from "@irtio/room";

const Ship = entity("ship", { captain: "string", x: "f32", z: "f32" }, { key: "captain" });

export default defineRoom({
  schema: defineSchema({ entities: [Ship] }),
  interest: grid({ cellSize: 250, range: 500, dims: "xz", around: (room, connection) => room.entities.get(Ship, connection.player) }),
  onJoin(room, connection) {
    if (!room.entities.get(Ship, connection.player)) room.entities.create(Ship, { captain: connection.player, x: Math.random() * 5000 });
  },
});

See also

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
grid()0.10.10.10.1