grid() function
Available since
@irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room hostThe 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, orundefined, in which case it subscribes only toEVERYWHERE. 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". Giverangeorradius, not both. radius- A whole number of cells. A connection sees every entity in the square, or cube, of cells within
radiuscells of its own on each axis. position(room, entity)Optional- An entity’s point
[x, y, z?], orundefinedfor none. Defaults to itsx,yandzfields. It places an entityaroundreturns too. prefixOptional- A string that starts every key the grid gives,
EVERYWHEREincluded, so two grids’ keys never meet. kindsOptional- The kinds the grid places. Other kinds get no key from it, and its
seeslets 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
optionshas bothrangeandradius, or neither. RangeError- Thrown for a
rangethat isn’t a finite number from 0, or aradiusthat 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 rooms | irt dev | @irtio/testing | Self-hosted room host | |
|---|---|---|---|---|
grid() | 0.1 | 0.1 | 0.1 | 0.1 |