Prediction: reckon() method

Available since @irtio/client 5.0BrowsersNode

The reckon() method of the Prediction interface returns a Reckoner that draws remote entities of a kind as the stepper moves them on the prediction world: on the local player’s timeline, where the room has them when the player’s input arrives.

Syntax

reckon(kind, fields)

Parameters

kind
The entity kind to draw, as entity() declared it.
fields
An array of the names of the kind’s numeric, angle and quat fields to draw. Any other field is a type error.

Return value

A Reckoner for the kind and fields. Call its get() each frame.

Exceptions

TypeError
Thrown if a field isn’t one of the kind’s fields, or isn’t a numeric, angle or quat field.

Description

Reckoning is for entities that move on their own, by rules the stepper knows, such as projectiles, falling crates and trains. Interpolation draws remote entities a little behind the room’s clock while the local player is predicted ahead of it, so a rocket the player dodges on screen would be drawn behind where the room has it. A reckoned rocket is drawn on the player’s own timeline instead.

Other players move only by their inputs, which the client doesn’t have, so reckoning them shows the room’s latest state with each update’s jump: interpolate them. Each input carries when reckoned entities were last drawn, which the room reads as connection.reckonTick for lag compensation.

Examples

Drawing rockets the player dodges

The stepper moves every rocket, so the client reckons them and interpolates the other pilots.

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

const Pilot = entity("pilot", { owner: "string", x: "f32", y: "f32" });
const Rocket = entity("rocket", { x: "f32", y: "f32", vx: "f32", vy: "f32" });
const schema = defineSchema({ entities: [Pilot, Rocket] });
const stepper = defineStepper<{ dy: number }>({
  step(world, inputs, dt) {
    for (const r of world.all(Rocket)) {
      r.x += r.vx * dt;
      r.y += r.vy * dt;
    }
    for (const p of world.all(Pilot)) p.y += (inputs.get(p.owner)?.dy ?? 0) * 6 * dt;
  },
});

const room = await connect("canyon", { schema });
const me = room.predict(stepper, {
  find: (r) => [...r.entities.all(Pilot)].find((p) => p.owner === r.player),
  sample: () => ({ dy: 0 }),
});
const rockets = me.reckon(Rocket, ["x", "y"]);
const pilots = room.interpolate(Pilot, ["x", "y"]);

function frame() {
  for (const r of room.entities.all(Rocket)) console.log("rocket", rockets.get(r));
  for (const p of room.entities.all(Pilot)) if (p.owner !== room.player) console.log("pilot", pilots.get(p));
  requestAnimationFrame(frame);
}
frame();

See also

Runtime availability

BrowsersNode
reckon()5.05.0