EntityStore: onCorrect() method
@irtio/client 5.0BrowsersNodeThe onCorrect() method of the EntityStore interface calls a function each time the room overrules the local player’s writes to an entity of a kind it owns, with the names of the corrected fields.
Syntax
onCorrect(kind, callback)
onCorrect(kind, callback, options)
Parameters
kind- A kind declared in the client’s schema, such as
schema.privatefor the private state. callback-
A function called with these parameters:
entity- The
OwnedEntitythe room corrected, typed as its kind, with the room’s values. corrected- An array of the names of the writable fields the room corrected.
optionsOptional-
An object with this property:
signal- An
AbortSignal. When it aborts, the callback is removed, asaddEventListener()removes a listener. If it has aborted already, the callback isn’t added.
Return value
A function that removes the callback.
Exceptions
Error- Thrown if the kind isn’t declared in the client’s schema.
Description
The owner of an entity keeps its own values for the writable fields it owns. When the room’s value differs from what the owner wrote, because the room’s writes handler clamped or rejected the write or room code wrote the field, the owner gets a correction:
- It overwrites the client’s copy with the room’s value and drops the client’s unsent writes to those fields.
onChange()runs for the fields first, thenonCorrect().- Every other client sees only the room’s value, and never a correction.
Use onCorrect() to snap or smooth what the player sees to the room’s value, or to tell the player why a move didn’t take.
Examples
Snapping a paddle back to the room’s position
The player drags their paddle, and the room clamps it to the table. When the room corrects it, the client moves the paddle’s sprite to the room’s value.
// paddle.ts
import { connect, defineSchema, entity } from "@irtio/client";
const Paddle = entity("paddle", { y: "f32" }, { writable: ["y"] });
const schema = defineSchema({ entities: [Paddle] });
const room = await connect("pong-7", { schema });
room.entities.onCorrect(Paddle, (paddle, corrected) => {
if (corrected.includes("y")) console.log(`snap paddle ${paddle.id} to ${paddle.y}`);
});
See also
OwnedEntityEntityStore.onChange()RoomDefinition.writes, the room’s side- Corrections
Runtime availability
| Browsers | Node | |
|---|---|---|
onCorrect() | 5.0 | 5.0 |