Prediction: push() method

Available since @irtio/client 5.0BrowsersNode

The push() method of the Prediction interface sends an input for the next room tick and steps the predicted entity with it.

Syntax

push(input)

Parameters

input
The input for this tick, of the stepper’s input type. With the schema’s input kind, an object of that kind’s fields; otherwise any value that serializes as JSON.

Return value

None (undefined).

Exceptions

TypeError
Thrown if the schema declares an input kind and input isn’t an object, or one of its fields is missing or of the wrong type.
RangeError
Thrown if the schema declares an input kind and a field is out of its type’s range, such as 300 for a u8, or a string, bytes or JSON field is over its limit.
IrtError
Thrown with the name InvalidStateError if the room has no ticks. predict() throws this too, but can’t tell before the room’s first welcome message, so a prediction made before then can reach push().

Description

With sample, the prediction calls push() itself once per room tick. Without sample, call it yourself once per room tick, such as from a fixed-step loop of your own.

push() does nothing unless the client’s readyState is "open", and does nothing once the prediction is stopped with stop(). Each input is for the room tick after the last one pushed, or the earliest tick it can reach the room in time for, whichever is later. Each message repeats the last 4 inputs, so a lost one costs nothing. With the schema’s input kind, the prediction steps with the fields as the room decodes them, so an f32 field rounds the same on both sides.

Examples

Pushing inputs from a fixed-step loop

A rhythm game pushes the lane the player holds from its own loop, once per room tick, rather than passing sample.

// lanes.ts
import { connect, defineSchema, defineStepper, entity } from "@irtio/client";

const Dancer = entity("dancer", { owner: "string", lane: "u8" });
const schema = defineSchema({ entities: [Dancer] });
const stepper = defineStepper<{ lane: number }>({
  step(world, inputs) {
    for (const d of world.all(Dancer)) d.lane = inputs.get(d.owner)?.lane ?? d.lane;
  },
});

const room = await connect("stage", { schema });
const me = room.predict(stepper, {
  find: (r) => [...r.entities.all(Dancer)].find((d) => d.owner === r.player),
});

let held = 0;
addEventListener("keydown", (e) => {
  if (e.key >= "1" && e.key <= "4") held = Number(e.key) - 1;
});
setInterval(() => me.push({ lane: held }), 1000 / room.tickRate);

A timer of your own drifts against the room’s clock, which sample follows, so prefer sample unless the game already runs a fixed step.

See also

Runtime availability

BrowsersNode
push()5.05.0