Appearance
@pawnjs/physics
Not on npm yet
This package comes with a later release of Pawn.
Rapier rigid bodies and colliders as traits, stepped in the fixedUpdate phase with the engine's fixed time step: primitive, mesh and terrain colliders, a character controller, collision events, raycasts and shape casts.
TypeScript
Rapier's types use Symbol.dispose. Unless skipLibCheck is on (the starter turns it on), add "ESNext" (or "ESNext.Disposable") to lib in tsconfig.json.
ts
import { Position, Rotation, Visual } from "@pawnjs/core";
import { Collider, createPhysics, RigidBody } from "@pawnjs/physics";
// Rapier loads its WASM module asynchronously (once per page).
const physics = await createPhysics({ gravity: { x: 0, y: -9.81, z: 0 } });
engine.use(physics);
// A fixed floor.
engine.world.spawn(
Position,
RigidBody({ type: "fixed" }),
Collider({ shape: { type: "cuboid", halfExtents: { x: 5, y: 0.2, z: 5 } } }),
Visual(floorMesh),
);
// A bouncing ball.
const ball = engine.world.spawn(
Position({ x: 0, y: 5, z: 0 }),
Rotation,
RigidBody,
Collider({ shape: { type: "ball", radius: 0.5 }, restitution: 0.6 }),
Visual(ballMesh),
);RigidBody
Fields left out keep their defaults (RigidBody({ type: "fixed" })):
| Field | Default | Meaning |
|---|---|---|
type | "dynamic" | "dynamic", "fixed", "kinematicPosition" or "kinematicVelocity". |
linearDamping | 0 | |
angularDamping | 0 | |
gravityScale | 1 | |
ccd | false | Continuous collision detection, for fast and small bodies. |
linearVelocity | { x: 0, y: 0, z: 0 } | Initial linear velocity. |
- The body starts at the entity's
PositionandRotation. - Dynamic and kinematic velocity bodies write their pose back to
PositionandRotationevery fixed step. - Kinematic position bodies follow
PositionandRotation; move them by writing those traits. - Setting
PositionorRotationof any other body, by hand, with a tween, another system orengine.restore(), moves the body there at the start of the next fixed step, or sooner when you callgetBody()orraycast(). - Setting
RigidBody(e.g.entity.set(RigidBody, { type: "fixed" })) applies it to the existing body;linearVelocitythen sets the body's velocity. - Bodies work in world space: put them on root entities, not on
ChildOfchildren.
Collider
A collider has a shape (default: a ball of radius 0.5) and material fields, e.g. Collider({ shape: { type: "ball", radius: 1 }, restitution: 0.6 }):
| Shape | Fields |
|---|---|
ball | radius |
cuboid | halfExtents: { x, y, z } |
capsule | halfHeight, radius |
cylinder | halfHeight, radius |
trimesh | vertices, indices: a triangle mesh (see Level geometry) |
heightfield | rows, columns, heights, size: { x, z }: a grid of heights (see Level geometry) |
| Material field | Default | Meaning |
|---|---|---|
density | 1 | |
friction | 0.5 | |
restitution | 0 | Bounciness. |
sensor | false | Sensors detect overlaps without producing contact forces. |
A Collider attaches to the entity's RigidBody. On an entity without one, it is a fixed collider at the entity's Position and Rotation, and moves when they change, the same way as a body. Setting Collider rebuilds the collider with the new shape and material.
Level geometry
A level modelled in three.js or a 3D tool (a skatepark, a building) collides as a trimesh, and terrain as a heightfield. Both are meant for fixed colliders (an entity without a RigidBody, or a fixed one) and kinematic bodies: they are hollow surfaces, so dynamic bodies collide with them but not with each other's meshes.
trimeshFromObject(object) makes a trimesh shape from the meshes of a three.js object, such as a Visual or a loaded glTF scene. It keeps the transforms between each mesh and object, in object's own space, so give the collider entity the pose the object has (here both sit on the same entity):
ts
import { Position, Visual } from "@pawnjs/core";
import { Collider, trimeshFromObject } from "@pawnjs/physics";
engine.world.spawn(
Position,
Collider({ shape: trimeshFromObject(park) }),
Visual(park),
);Hidden objects, instanced and batched meshes, points and lines are left out; a geometry's drawRange is kept. A trimesh can also be written by hand, three numbers per vertex and three indices per triangle: { type: "trimesh", vertices: [x0, y0, z0, x1, ...], indices: [0, 1, 2, ...] }.
A heightfield is a grid of rows by columns heights (at least 2 each), centered on the entity and spanning size.x by size.z meters. Rows run from -z to +z and columns from -x to +x: the height at row, column is heights[row * columns + column], in meters. It matches the vertices of a three.js PlaneGeometry(size.x, size.z, columns - 1, rows - 1) rotated flat with rotateX(-Math.PI / 2):
ts
import { Position, Visual } from "@pawnjs/core";
import { Collider } from "@pawnjs/physics";
import { Mesh, MeshStandardMaterial, PlaneGeometry } from "three";
const rows = 33;
const columns = 33;
const heights: number[] = [];
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
heights.push(Math.sin(column * 0.4) * Math.cos(row * 0.3));
}
}
const plane = new PlaneGeometry(40, 40, columns - 1, rows - 1);
plane.rotateX(-Math.PI / 2);
heights.forEach((h, i) => {
plane.attributes.position?.setY(i, h);
});
plane.computeVertexNormals();
engine.world.spawn(
Position,
Collider({
shape: { type: "heightfield", rows, columns, heights, size: { x: 40, z: 40 } },
}),
Visual(new Mesh(plane, new MeshStandardMaterial())),
);Both shapes smooth contacts across the edges between their triangles, so balls roll and characters walk over them without catching. Their numbers are trait data, so snapshots save every vertex and height. A trimesh without triangles or with an index that is not one of its vertices, or a heightfield whose heights is not rows * columns long, makes no collider: the entity keeps its Collider and a warning names the problem.
Character controller
A character walked by a player (or by a game's AI) is moved by code, not by forces, but still has to stop at walls and stand on the ground. CharacterController makes an entity's collider one that physics.moveCharacter(entity, translation) moves by a wanted translation: it slides along walls, climbs steps, follows the ground down steps and slopes, and reports whether the character stands on the ground.
Give the character a kinematicPosition RigidBody (or no body) and a collider, usually a capsule, and move it from a fixedUpdate system that runs before the physics step:
ts
const hero = engine.world.spawn(
Position({ y: 1 }),
RigidBody({ type: "kinematicPosition" }),
Collider({ shape: { type: "capsule", halfHeight: 0.5, radius: 0.4 } }),
CharacterController({ maxStepHeight: 0.3 }),
);
let fall = 0; // vertical speed, m/s
let grounded = false;
engine.addSystem(
({ delta }) => {
const x = +keys.isDown("KeyD") - +keys.isDown("KeyA");
const z = +keys.isDown("KeyS") - +keys.isDown("KeyW");
fall -= 9.81 * delta;
if (keys.isDown("Space") && grounded) fall = 5;
const move = physics.moveCharacter(hero, {
x: x * 4 * delta,
y: fall * delta,
z: z * 4 * delta,
});
grounded = move.grounded;
// Standing: stop falling, or gravity keeps pressing into the ground.
if (move.grounded && fall < 0) fall = 0;
},
{ phase: "fixedUpdate", order: Physics.ORDER - 1 },
);moveCharacter() adds what the character could move to its Position; its kinematic body glides there in the physics step. Other bodies, dynamic ones too, block it like walls. It returns { translation, grounded, groundNormal }:
| Field | Meaning |
|---|---|
translation | What it moved, a three.js Vector3: the wanted translation after walls and steps. |
grounded | Whether it stands on ground no steeper than maxSlopeClimbAngle. |
groundNormal | Up normal of that ground, e.g. to tilt a board along a ramp; zero when not grounded. A character that touched no ground while moving (standing still) probes below itself for it. |
CharacterController fields (set them like any trait; the controller follows):
| Field | Default | Meaning |
|---|---|---|
offset | 0.02 | Gap in meters kept between the character and what it touches. |
maxStepHeight | 0.3 | Highest step in meters it climbs (0 climbs none). |
minStepWidth | 0.2 | Narrowest step top it climbs onto, so it does not climb thin edges. |
snapToGround | 0.3 | Drop in meters it follows down to the ground instead of leaving it, down steps and slopes (0 for none). |
maxSlopeClimbAngle | Math.PI / 4 | Steepest slope it walks up, in radians. |
minSlopeSlideAngle | Math.PI / 4 | Slopes at least this steep slide it down. |
- The world's up is +y. Sensors do not block the character.
- While it rises (
yabove 0) it does not snap to the ground, so a jump keeps its height. - The horizontal part of the translation moves first, climbing steps, then the vertical part (a fall or a jump) from where that ended.
- Like
raycast(), it sees colliders as of the last physics step. - It throws for an entity without a
CharacterController, aCollideror aPosition, for a body that is notkinematicPosition, and for a translation that is not finite.
Snapshots
Physics registers RigidBody, Collider and CharacterController in engine.traits when it is installed, as rigid-body, collider and character-controller, so snapshots save them. Restore into an engine with a Physics installed: the bodies and colliders are made as the traits are added. Restoring into the same engine puts existing bodies back at their saved pose, with the saved RigidBody and Collider. Fields are checked like other traits (type must be one of the four body types, damping and material at least 0); linearVelocity and the collider shape are only checked for being set.
Collision events
After each physics step, collisionstart and collisionend are emitted on both entities of a pair through engine.events, and bubble up ChildOf like other entity events:
ts
engine.events.on(ball, "collisionstart", (e) => {
if (e.other === goal) score += 1;
});| Field | Meaning |
|---|---|
other | The other entity. On collisionend it may already be destroyed. |
sensor | Whether either collider is a sensor: an overlap, not a contact. |
- Listeners run in
fixedUpdate, after the bodies' poses are written back, soPositionandRotationare current. - Destroying an entity or removing its
Colliderends its collisions; the other entity getscollisionendon the next step. - A sensor is a
Colliderwithsensor: true: a trigger zone that reports what enters and leaves it without pushing back. - Solid colliders report pairs where at least one body is dynamic; two fixed or kinematic colliders never collide. Sensors also report kinematic and fixed bodies, so a kinematic character can walk into a trigger zone.
- A collider that is re-created in place (a
RigidBodyadded to an entity that already has aCollider) keeps its contacts without an end and a new start.
Raycast
physics.raycast(origin, direction, options?) returns the first collider a ray hits, or null:
ts
const hit = physics.raycast(player.get(Position)!, { x: 0, y: -1, z: 0 }, {
maxDistance: 1.2,
exclude: player,
});
const grounded = hit !== null;| Option | Default | Meaning |
|---|---|---|
maxDistance | Physics.DEFAULT_MAX_DISTANCE (1000) | Longest distance in meters. |
includeSensors | false | Whether sensors can be hit. |
exclude | An entity whose body and collider the ray ignores. | |
solid | true | Whether a ray starting inside a collider hits it at distance 0 (with a zero normal). |
A hit is { entity, point, normal, distance }, with point and normal as three.js Vector3 in world space. direction need not be normalized. Raycasts see colliders as of the last physics step: a collider added since is hit after the next step. For picking under the pointer, use the engine's picking (Views and picking); it works on what is drawn, not on colliders.
Shape cast
physics.castShape(shape, origin, direction, options?) moves a shape, as a Collider takes it, along a direction and returns the first collider it touches, or null. It is a raycast with thickness: a probe as wide as a character's feet finds a ledge a ray down its middle misses.
ts
const below = physics.castShape(
{ type: "ball", radius: 0.3 },
feet,
{ x: 0, y: -1, z: 0 },
{ maxDistance: 1, exclude: player },
);The options are rotation (a quaternion, of the shape), maxDistance, includeSensors and exclude, as for raycast(). The hit has the same fields, with point and normal on the collider hit, and distance how far the shape moved before touching it.
Rapier access
For queries, joints, forces and anything else Rapier offers, use the underlying objects:
ts
physics.rapierWorld; // RAPIER.World
physics.getBody(ball); // RAPIER.RigidBody | undefined
physics.getCollider(ball); // RAPIER.Collider | undefined
physics.getBody(ball)?.applyImpulse({ x: 0, y: 5, z: 0 }, true);A physics plugin can be installed on one engine; engine.dispose() frees its Rapier world. Create a new one with createPhysics() for another engine.