RoomClient: predict() method
@irtio/client 5.0BrowsersNodeThe predict() method of the RoomClient interface predicts an entity this client controls, such as the local player, with the stepper the room runs. It returns a Prediction that steps the entity ahead of the room’s state as the player gives inputs.
Syntax
predict(stepper, options)
Parameters
stepper- The stepper the room passes to
defineRoom(), made withdefineStepper(). options-
An object with these properties:
find- A function that takes the client and returns the entity to predict from the client’s view, such as the local player’s, or
undefinedwhile it isn’t there. sampleOptional- A function that takes the
Predictionand returns this tick’s input. The prediction calls it once per room tick, by the client’s estimate of the room’s clock, first at the next tick afterpredict()returns, and sends the input. The prediction’sentityis set before each call wheneverfindfinds the entity. Withoutsample, call the prediction’spush()once per tick. idleOptional- A function that takes an input and returns whether it means the same as sending none, such as standing still. An idle input isn’t sent once the room has acknowledged every input sent before it, and both sides step that tick with no input, so the stepper must treat a missing input as the idle one.
warnOnDivergenceOptional- A boolean. If
true, the prediction logs a console warning, naming the fields, each time itsdriftverdict turns"diverging". Defaults tofalse.
Return value
A Prediction, typed by the kind find returns.
Exceptions
IrtError- Thrown with the name
InvalidStateErrorif the room has no ticks, since inputs are counted in the room’s ticks. Before the room’s firstwelcomemessage, the client can’t tell, so it doesn’t throw. Error- Thrown if this client already has a prediction that hasn’t been stopped, since two predictions would each send an input for the same ticks. Call the old one’s
stop()first.
Description
The prediction steps the entity with each input as soon as the player gives it, then, each time the room acknowledges inputs, replays the ones it hasn’t acknowledged yet on top of the room’s state. When the room’s state differs from what it predicted, it counts a misprediction, and render() smooths the correction away over the next frames. Client prediction explains inputs, acknowledgements and replay in full.
room.predictions holds every prediction predict() made on the client, stopped ones included. For remote entities, use interpolate(), or the prediction’s reckon() for those the stepper moves.
Examples
Predicting the local paddle
In a game of pong, each player moves their own paddle with the arrow keys. The stepper is shared with the room, and its parseInput() refuses any input but -1, 0 or 1, so a player can’t send a faster move.
// paddle.ts
import { connect, defineSchema, defineStepper, entity } from "@irtio/client";
const Paddle = entity("paddle", { owner: "string", y: "f32" });
const schema = defineSchema({ entities: [Paddle] });
// The room passes the same stepper to defineRoom()
const stepper = defineStepper<{ dy: number }>({
parseInput(raw) {
const dy = (raw as { dy?: unknown }).dy;
if (dy !== -1 && dy !== 0 && dy !== 1) throw new RangeError("dy is -1, 0 or 1");
return { dy };
},
step(world, inputs, dt) {
for (const paddle of world.all(Paddle)) paddle.y += (inputs.get(paddle.owner)?.dy ?? 0) * 8 * dt;
},
});
const room = await connect("pong", { schema });
const keys = new Set<string>();
addEventListener("keydown", (e) => keys.add(e.key));
addEventListener("keyup", (e) => keys.delete(e.key));
const me = room.predict(stepper, {
find: (r) => [...r.entities.all(Paddle)].find((p) => p.owner === r.player),
sample: () => ({ dy: (keys.has("ArrowDown") ? 1 : 0) - (keys.has("ArrowUp") ? 1 : 0) }),
idle: (input) => input.dy === 0,
});
Each frame, the game draws the paddle where the prediction has it:
const { y } = me.render(["y"]);
See also
Runtime availability
| Browsers | Node | |
|---|---|---|
predict() | 5.0 | 5.0 |