Prediction: snap() method
Available since
@irtio/client 5.0BrowsersNodeThe snap() method of the Prediction interface drops every misprediction render() is smoothing, so it draws the predicted entity as it is, such as after a respawn.
Syntax
snap()
Parameters
None.
Return value
None (undefined).
Exceptions
None.
Description
A respawn or teleport that room code makes arrives as a misprediction, which render() would otherwise slide the player across. snap() also resets drift, since a respawn isn’t drift.
The misprediction lands when the room’s acknowledgement arrives, after the tick’s state update, so watch a field the room sets with the jump and snap in the frame where entity shows its new value. Where no field says so, pass a snapDistance to render() instead.
Examples
Snapping after a respawn
The room counts each respawn in a lives field, so the client snaps when it changes.
// respawn.ts
import { connect, defineSchema, defineStepper, entity } from "@irtio/client";
const Diver = entity("diver", { owner: "string", depth: "f32", lives: "u8" });
const schema = defineSchema({ entities: [Diver] });
const stepper = defineStepper<{ swim: number }>({
step(world, inputs, dt) {
for (const d of world.all(Diver)) d.depth += (inputs.get(d.owner)?.swim ?? 0) * 3 * dt;
},
});
const room = await connect("reef", { schema });
const me = room.predict(stepper, {
find: (r) => [...r.entities.all(Diver)].find((d) => d.owner === r.player),
sample: () => ({ swim: 1 }),
});
let lives: number | undefined;
function frame() {
if (me.entity && me.entity.lives !== lives) {
lives = me.entity.lives;
me.snap();
}
console.log(me.render(["depth"]).depth);
requestAnimationFrame(frame);
}
frame();
See also
Runtime availability
| Browsers | Node | |
|---|---|---|
snap() | 5.0 | 5.0 |