Entities

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

The Entities interface of the Room API holds a room’s entities: it creates and deletes them, finds them by ID, key or kind, and gives them to players. Each room has one, as room.entities.

It’s also the world the room’s stepper gets, so a stepper reads and writes the same entities as the hooks do.

What it holds:

  • Every entity the room created and hasn’t deleted, of every kind in the schema’s entities, hidden kinds included.
  • Not room.state, private state or presence entries. Only get() with ID 0 and all() of the shared state kind give room.state, as a stepper’s world does on the client too.

Each entity is a RoomEntity. Entities are room state: they’re saved, restored on wake and kept across a room host crash, with their IDs, keys and owners.

Instance properties

Entities.count
The number of entities. Read only.

Instance methods

Entities.create()
Creates an entity of a kind and returns it.
Entities.delete()
Deletes an entity.
Entities.get()
Returns the entity with an ID, or the entity of a kind with a key.
Entities.all()
Returns an iterator over every entity of a kind.
Entities.setOwner()
Gives an entity to a player, or back to the room.
Entities.ownerOf()
Returns the player who owns an entity, or undefined for the room.
Entities.ownedBy()
Returns an iterator over the entities of a kind a player owns.

Examples

Spawning and collecting coins

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

const Coin = entity("coin", { x: "f32", y: "f32", value: "u8" });

export default defineRoom({
  schema: defineSchema({ entities: [Coin] }),
  onCreate(room) {
    for (let i = 0; i < 10; i++) room.entities.create(Coin, { x: i * 5, y: 0, value: 1 });
  },
  onMessage(room, connection, message) {
    const id = (message as { collect?: unknown } | null)?.collect;
    const coin = typeof id === "number" ? room.entities.get(id) : undefined;
    if (coin?.kind !== Coin) return;
    room.entities.delete(coin);
    room.send(connection, { type: "collected", left: [...room.entities.all(Coin)].length });
  },
});

See also

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
Entities0.10.10.10.1