Prediction: render() method

Available since @irtio/client 5.0BrowsersNode

The render() method of the Prediction interface returns fields of the predicted entity for drawing: the prediction plus a decaying share of recent mispredictions, so a correction eases in rather than jumps.

Syntax

render(fields)
render(fields, options)

Parameters

fields
An array of the names of the kind’s numeric, angle and quat fields. Any other field is a type error.
options Optional

An object with this property:

snapDistance
A number. A misprediction of the listed numeric fields longer than this, measured as a Euclidean distance over them, is dropped instead of smoothed, as after a teleport, and so is the listed quat fields’ with it.

Return value

An object with each listed field: a number for a numeric or angle field, and a Quat for a quat field.

Before the first input, it’s the room’s state of the entity. While find finds nothing, each listed field is NaN, quat fields included.

Exceptions

None.

Description

Each tick, the share of a misprediction that render() still adds shrinks by 20%. An angle correction turns the short way round, and a quat correction is a rotation smoothed back toward none.

A misprediction dropped for snapDistance resets drift too, since a teleport isn’t drift. To drop every correction at once, call snap().

Examples

Drawing a kart that respawns

A kart drawn each frame from render(). A respawn moves it across the track, which snapDistance draws at once rather than sliding.

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

const Kart = entity("kart", { owner: "string", x: "f32", y: "f32", heading: "angle" });
const schema = defineSchema({ entities: [Kart] });
const stepper = defineStepper<{ steer: number }>({
  step(world, inputs, dt) {
    for (const k of world.all(Kart)) {
      k.heading += (inputs.get(k.owner)?.steer ?? 0) * 2 * dt;
      k.x += Math.cos(k.heading) * 10 * dt;
      k.y += Math.sin(k.heading) * 10 * dt;
    }
  },
});

const room = await connect("circuit", { schema });
const me = room.predict(stepper, {
  find: (r) => [...r.entities.all(Kart)].find((k) => k.owner === r.player),
  sample: () => ({ steer: 0 }),
});

function frame() {
  const kart = me.render(["x", "y", "heading"], { snapDistance: 30 });
  console.log(kart.x, kart.y, kart.heading);
  requestAnimationFrame(frame);
}
frame();

See also

Runtime availability

BrowsersNode
render()5.05.0