RoomDefinition: onPlayerLeave() hook
@irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room hostThe onPlayerLeave() hook of a room definition runs once when a player’s presence in the room ends. It’s the place to delete a player’s avatar, which then survives a dropped network and a quick reconnect.
Syntax
defineRoom({
onPlayerLeave(room, player) {},
});
Parameters
room- The
Room. player- The ID of the player whose presence ended.
Return value
None, or a Promise, which the room doesn’t wait for.
Exceptions
If onPlayerLeave throws, or its promise rejects, the error is logged. The room keeps running.
Description
A player’s presence ends:
- at once after the player’s client closed with
client.close(); PRESENCE_GRACE, 10 seconds, after its last connection dropped with no new one;- when the room removes a bot with
room.bots.remove(), or when a person takes a bot’s seat.
Until the hook first awaits, the player’s presence entry is still in room.presence, with connected false, so its name is there to read. The entry no longer holds a seat, so room.bots.add() can fill it.
Once the hook returns or first awaits, each kind’s onOwnerLeave rule applies to what the player still owns; see When the owner leaves. So onPlayerLeave can still give an entity to someone else before the rule takes it.
Before the room hibernates, onPlayerLeave runs for every person still in presence, after onLeave() for each connection, with every entry connected false. It doesn’t run for bots then, nor when the room goes to sleep, and the onOwnerLeave rules don’t apply at a hibernation.
It never runs after a room host crash: the room restarts with presence empty, so a player who doesn’t come back gets no onPlayerLeave. A room that cares removes, in onTick or onAlarm, what belongs to players who have been gone a while.
Examples
Passing on the host role
// host-role.ts
import { defineRoom, defineSchema, entity } from "@irtio/room";
const Lobby = entity("lobby", { host: "string" });
export default defineRoom({
schema: defineSchema({ state: Lobby }),
onJoin(room, connection) {
if (room.state.host === "") room.state.host = connection.player;
},
onPlayerLeave(room, player) {
if (room.state.host !== player) return;
const next = [...room.presence].find((entry) => entry.connected && entry.player !== player);
room.state.host = next?.player ?? "";
},
});
See also
Runtime availability
| Hosted rooms | irt dev | @irtio/testing | Self-hosted room host | |
|---|---|---|---|---|
onPlayerLeave() | 0.1 | 0.1 | 0.1 | 0.1 |