Entities: ownedBy() method

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

The ownedBy() method of the Entities interface returns an iterator over the entities of a kind that a player owns.

Syntax

ownedBy(player, kind)

Parameters

player
The player ID.
kind
The kind of entities to list.

Return value

An iterator of RoomEntity objects of kind, which yields nothing for a player who owns none. It doesn’t include the player’s private state.

Description

The room keeps an index by owner, so ownedBy() visits only what the player owns, not every entity of the kind. Ownership survives reconnects and hibernation, so onJoin can find what a returning player already owns.

Examples

Capping the towers a player can build

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

const Tower = entity("tower", { x: "i16", y: "i16" });
const MAX_TOWERS = 5;

export default defineRoom({
  schema: defineSchema({ entities: [Tower] }),
  onMessage(room, connection, message) {
    const at = (message as { build?: { x: number; y: number } } | null)?.build;
    if (!at || !Number.isInteger(at.x) || !Number.isInteger(at.y)) return;
    if ([...room.entities.ownedBy(connection.player, Tower)].length >= MAX_TOWERS) {
      room.send(connection, { type: "error", reason: "tower limit" });
      return;
    }
    room.entities.create(Tower, { x: at.x, y: at.y }, { owner: connection.player });
  },
});

See also

Runtime availability

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