Skip to content
Jami3D
Developer docs menu

Colliders, physics and navigation

Hand a game package's colliders to your physics engine, walk a player on its ground and find paths on its navmesh, with a whole Rapier adapter.

Colliders

A package's colliders come from its scene's collision proxies, and its trigger zones from its zone proxies. world.colliders() hands them to your physics as plain descriptors, placed where their entities stand now, in world metres:

ShapeFields
boxhalfExtents
sphereradius
capsuleradius, halfHeight (half its core, along its local Y)
planehalfExtents (a box 1 cm thick)
meshvertices, indices (triangles in its own frame, scaled)

Each has entity (its key), shape, trigger, position and rotation (a quaternion x, y, z, w). A mesh's triangles are copied at each call: read them once, and follow the entity's object after that. Triggers are the runtime's: it tells when something enters or leaves one (an event), so a physics adapter skips them.

A Rapier adapter

Rapier (@dimforge/rapier3d-compat, Apache-2.0) takes the descriptors as they are. Install it beside the runtime:

Terminal
npm install @dimforge/rapier3d-compat
physics.ts
import RAPIER from "@dimforge/rapier3d-compat";
import type { ColliderDescriptor, GameWorld } from "@jami3d/three";

function shapeOf(collider: ColliderDescriptor): RAPIER.ColliderDesc | null {
  switch (collider.shape) {
    case "box":
    case "plane": {
      const [x, y, z] = collider.halfExtents ?? [0, 0, 0];
      return RAPIER.ColliderDesc.cuboid(x, y, z);
    }
    case "sphere":
      return RAPIER.ColliderDesc.ball(collider.radius ?? 0);
    case "capsule":
      return RAPIER.ColliderDesc.capsule(collider.halfHeight ?? 0, collider.radius ?? 0);
    case "mesh":
      return collider.vertices && collider.indices
        ? RAPIER.ColliderDesc.trimesh(collider.vertices, collider.indices)
        : null;
    default:
      return null; // a shape a later runtime adds
  }
}

/** A Rapier world holding the package's solid colliders, where their entities stand now. */
export async function physicsOf(world: GameWorld): Promise<RAPIER.World> {
  await RAPIER.init();
  const physics = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
  for (const collider of world.colliders()) {
    const shape = shapeOf(collider);
    if (collider.trigger || shape === null) continue; // the runtime tells triggers itself
    const [x, y, z] = collider.position;
    const [qx, qy, qz, qw] = collider.rotation;
    const body = physics.createRigidBody(
      RAPIER.RigidBodyDesc.kinematicPositionBased()
        .setTranslation(x, y, z)
        .setRotation({ x: qx, y: qy, z: qz, w: qw }),
    );
    physics.createCollider(shape, body);
  }
  physics.step(); // the colliders join Rapier's queries only once its world has stepped
  return physics;
}

Each solid collider becomes a kinematic body where its entity stands now. The adapter places each body once: an entity your game moves later needs its body moved with it.

A walking player

A kinematic character controller slides the player along those colliders while the package's ground holds it up. walker answers a function that moves your player by dx and dz metres:

walker.ts
import RAPIER from "@dimforge/rapier3d-compat";
import type { GameWorld } from "@jami3d/three";
import type { Object3D } from "three";

/** Moves the player by (dx, dz) metres: slid along the colliders, stood on the package's ground. */
export function walker(physics: RAPIER.World, world: GameWorld, player: Object3D) {
  const collider = physics.createCollider(RAPIER.ColliderDesc.capsule(0.5, 0.35));
  const controller = physics.createCharacterController(0.02);
  controller.setSlideEnabled(true);
  return (dx: number, dz: number) => {
    const feet = player.position;
    collider.setTranslation({ x: feet.x, y: feet.y + 0.85, z: feet.z });
    controller.computeColliderMovement(collider, { x: dx, y: 0, z: dz });
    const moved = controller.computedMovement();
    const ground = world.heightAt(feet.x + moved.x, feet.z + moved.z);
    if (ground !== null) player.position.set(feet.x + moved.x, ground, feet.z + moved.z);
  };
}

Step the physics world once a frame, so the colliders stand where their bodies were last put. With the quickstart's renderer, scene, camera and world, and a player of yours:

game.ts
import { physicsOf } from "./physics";
import { walker } from "./walker";

const physics = await physicsOf(world);
const move = walker(physics, world, player);
const held = new Set<string>();
addEventListener("keydown", (event) => held.add(event.code));
addEventListener("keyup", (event) => held.delete(event.code));

let last = performance.now();
renderer.setAnimationLoop((now: number) => {
  const dt = Math.min(0.1, Math.max(0, now - last) / 1000);
  last = now;
  const ahead = (held.has("KeyS") ? 1 : 0) - (held.has("KeyW") ? 1 : 0);
  const side = (held.has("KeyD") ? 1 : 0) - (held.has("KeyA") ? 1 : 0);
  move(side * 4 * dt, ahead * 4 * dt); // 4 m/s
  physics.step();
  world.update(dt, camera); // living bodies, clips, sky and water move on
  renderer.render(scene, camera);
});

The ground

world.heightAt(x, z) answers the ground's height: the navmesh's floor, else the terrain's, else null off the world. world.raycast(origin, direction, { maxM?, triggers?, ground? }) answers the nearest hit on the colliders and the ground, its entity null for the ground.

The navmesh and its floor are the scene's as baked: over a floor left out of the package, heightAt still answers that floor and living bodies still walk on it. Bake the navmesh again without it, or keep the floor.

TypeScript
const ground = world.heightAt(4, -2); // the navmesh's floor, else the terrain's; null off the world
const hit = world.raycast([0, 10, 0], [0, -1, 0], { maxM: 50 }); // colliders and the ground
if (hit !== null) console.log(hit.point, hit.normal, hit.distanceM, hit.entity ?? "the ground");
console.log(ground);

Other physics engines

cannon-es, Ammo or your own engine map the same descriptors: a box's half extents, a sphere's radius, a capsule's radius and half core height along its Y, a trimesh's vertices and indices, each at its position and rotation.

A world with a navmesh (its scene's baked one) answers paths over it. findPath(from, to, { areaCosts }) prices the navmesh's areas by name — ground, path, rock, vegetation, structure, underCanopy — and uses the world's own costs without areaCosts. A path is null off the navmesh, and its complete is false when it ends short of to. randomPoint draws from the world's seeded stream: the same seed gives the same points.

TypeScript
if (world.nav.ready) {
  const path = world.nav.findPath([0, 0, 20], [16, 0, -18], { areaCosts: { rock: 4 } });
  if (path !== null) console.log(path.points, path.complete); // complete: false when it ends short
  const spot = world.nav.randomPoint({ around: [0, 0, 0], radiusM: 10 }); // the world's seeded stream
  console.log(spot);
}

Living bodies

The package's living bodies — people and animals that idle, wander, patrol, go to, follow, pursue, flee, herd and use places — walk on its navmesh and ground by themselves, at a fixed 30 Hz on the world's time, as JAMI's Live Room plays them with the same seed. Your game does not step them and needs no physics engine for them: name their host targets, write their params, and hear their life events. They walk on the navmesh, not in your physics world: your bodies do not push them.