Prediction: entity property
@irtio/client 5.0BrowsersNodeThe entity read-only property of the Prediction interface is the predicted entity: the room’s last state of it plus the inputs the room hasn’t acknowledged.
Value
An entity of the kind find returns, with its fields as properties and a toJSON() method as client entities have, or undefined.
It’s undefined while find finds nothing: before the entity enters the client’s view, while the room has deleted it and after a reconnect until the full state arrives. Before each call to sample, it’s set whenever find finds the entity.
Description
Use entity for game logic, such as steering by where the player is, and render() for drawing, since entity jumps when a replay corrects it. Its fields are the stepper’s to write: game code reads them.
Examples
Steering towards a flag
A capture-the-flag runner’s sample reads its predicted position to steer at the flag.
// flag-runner.ts
import { connect, defineSchema, defineStepper, entity } from "@irtio/client";
const Runner = entity("runner", { owner: "string", x: "f32" });
const schema = defineSchema({ entities: [Runner] });
const stepper = defineStepper<{ dir: number }>({
step(world, inputs, dt) {
for (const r of world.all(Runner)) r.x += (inputs.get(r.owner)?.dir ?? 0) * 5 * dt;
},
});
const FLAG_X = 40;
const room = await connect("ctf", { schema });
const me = room.predict(stepper, {
find: (r) => [...r.entities.all(Runner)].find((e) => e.owner === r.player),
// Undefined before the runner is in view, so stand still until then
sample: (p) => ({ dir: Math.sign(FLAG_X - (p.entity?.x ?? FLAG_X)) }),
});
See also
Prediction.render(), for drawingPrediction.settled- Client prediction
Runtime availability
| Browsers | Node | |
|---|---|---|
entity | 5.0 | 5.0 |