RoomClient: interpolate() method
@irtio/client 5.0BrowsersNodeThe interpolate() method of the RoomClient interface records the listed fields of every entity of a kind as state updates arrive, and returns an Interpolator that gives their values between updates, for rendering.
Syntax
interpolate(kind, fields)
Parameters
kind- The entity kind, made with
entity()in the room’s schema. fields- An array of the names of the kind’s fields to interpolate. Each is a numeric,
angleorquatfield. Any other is a type error.
Return value
An Interpolator, whose get() takes an entity of the kind and returns the listed fields at the client’s render time.
Exceptions
IrtError- Thrown with the name
InvalidStateErrorif the room has no ticks, since the render time is counted in the room’s ticks. Before the room’s firstwelcomemessage, the client can’t tell, so it doesn’t throw. TypeError- Thrown if a field isn’t one of the kind’s, or isn’t a numeric,
angleorquatfield.
Description
The render time is the room’s estimated tick, from serverTick(), less two ticks or 100 ms, whichever is longer. get() returns each field linearly between the two states around it, so call it each frame. Entities already in the client’s view when interpolate() is called are recorded from then.
An angle field goes the short way round where it wraps. A quat field goes by normalized linear interpolation on the same side as the earlier state, so a rotation whose sign flips between states doesn’t spin.
Interpolate remote entities. For the local player, use predict(), which shows the player’s inputs at once rather than a render time behind.
Examples
Drawing the other ships
A space game draws every other player’s ship between the room’s updates, turning each by its angle heading. The local ship is drawn from its prediction.
// ships.ts
import { connect, defineSchema, entity } from "@irtio/client";
const Ship = entity("ship", { owner: "string", x: "f32", y: "f32", heading: "angle" });
const schema = defineSchema({ entities: [Ship] });
const room = await connect("sector-9", { schema });
const ships = room.interpolate(Ship, ["x", "y", "heading"]);
const canvas = document.querySelector("canvas")!.getContext("2d")!;
function frame() {
canvas.clearRect(0, 0, 800, 600);
for (const ship of room.entities.all(Ship)) {
if (ship.owner === room.player) continue;
const { x, y, heading } = ships.get(ship);
canvas.setTransform(1, 0, 0, 1, x, y);
canvas.rotate(heading);
canvas.fillRect(-12, -6, 24, 12);
}
canvas.resetTransform();
requestAnimationFrame(frame);
}
frame();
See also
InterpolatorRoomClient.predict()- Client prediction, for the local player
- State sync and interest
Runtime availability
| Browsers | Node | |
|---|---|---|
interpolate() | 5.0 | 5.0 |