# Physics

A cart gets a physics world from one hook: boxes that fall and stack, a character that walks up steps and slides along walls, rays for line of sight, triggers for pickups, and paths around the level for anything that chases you. The same names work in 3D, with `useWorld`, and on the 2D stage, with `useWorld2D`.

```tsx
import { useEffect } from "react"
import { mount, useScene, useModel, useWorld } from "oj"

function Yard() {
    const scene = useScene()
    const crate = useModel("crate.glb")
    const world = useWorld()

    useEffect(() => {
        if (!scene || !crate || !world) return
        world.box({ at: [0, -0.5, 0], size: [20, 1, 20] })    // the floor
        for (let i = 0; i < 10; i++) {
            world.box({ at: [0, 1 + i, 0], dynamic: true, actor: scene.spawn(crate) })
        }
    }, [scene, crate, world])

    return null
}

mount(<Yard />)
```

`useWorld()` is `null` until the engine has loaded, one download the first time a cart makes a world, so wait for it as you wait for the scene. It steps itself every frame and is gone with the component.

Give a body an `actor` and the world moves that model to wherever the body is, every frame, at no cost to your code. The actor sits at the body's centre, so a model whose origin is at its feet needs a body whose centre is where the model's middle is. A character's actor sits at its feet, where a figure's origin usually is.

On a screen faster than 60 Hz the world steps every other frame or so, and draws each actor between where its last two steps left it, so it moves on every frame and never anywhere the engine did not take it. That puts the model up to a step behind `body.position`, a sixtieth of a second, so a camera that follows something follows its model: `body.actor.position`.

Metres, y up and degrees, the same as the scene, so a body and a model agree with nothing to convert. The Falling Boxes example is this page's first section as a whole cart.

## Bodies

```tsx
world.box({ at: [0, 1, 4], size: [8, 2, 1] })                     // a wall: static by default
world.sphere({ at: [0, 3, 0], radius: 0.3, dynamic: true, bounce: 0.8 })
world.capsule({ at: [2, 1, 0], radius: 0.3, height: 1.6, kinematic: true })
const level = await world.mesh(arena, { at: [0, 0, 0] })          // every triangle of a model
const ground = world.heightfield({ at: [0, 0, 0], size: [64, 64], heights })   // terrain, from a grid of heights
```

A body is one of three things:

| | |
|---|---|
| Static | Scenery. The default, because most of a level never moves |
| `dynamic: true` | Moved by the simulation: falls, is pushed, bounces, tumbles |
| `kinematic: true` | Moved by you, and pushes dynamic bodies out of its way: doors, lifts, platforms |

`friction` (0 is ice, 0.5 by default) and `bounce` (0 is dead, 1 bounces back as high; of two bodies that meet, the bouncier wins) tune how a body feels. A dynamic body weighs what its size does at `density`, 500 kilograms a cubic metre by default, like wood: a 1 m crate is 500 kg. Set `mass` to give it a weight of your own.

`drag` slows a body by itself, moving and turning: at 1 it loses about two thirds of its speed in a second, which is how a puck on a table or a ship in space comes to rest. `rotates: false` lets it move but never turn, like a crate that slides rather than tumbles. Both can be set later on the body. `fast: true` is for something small and quick, a shot or a puck: it is swept along its path each step, so it cannot pass through another moving body between two steps. A static wall stops everything without it, and it costs a little each step, so leave it off for anything else.

A body's `position`, `rotation` and `velocity` read and write. Writing `position` teleports it; on a kinematic body it travels there over the next step, pushing what is in the way. `rotation` takes any of `yaw`, `pitch` and `roll`, the rest 0. `addVelocity([0, 5, 0])` throws anything up at 5 metres a second more, whatever it weighs; `push([0, 500, 0])` is a shove in kilogram metres a second, so it throws a 500 kg crate at 1 m/s and a light ball much faster. `destroy()` removes it, and its actor with it.

A kinematic body keeps a velocity you give it: `lift.velocity = [0, 1, 0]` raises it a metre a second until you change it, which is all a lift, a platform or a sliding door needs. A static body does not move, and setting its velocity or pushing it throws. A character standing on a moving body rides along with it, as a player on a lift should.

`world.mesh` takes a model from `useModel`, a `.glb` by name, or triangles, and places it as `scene.spawn` would. Use it for the level itself, ramps and rocks: anything whose shape a box would get wrong. A mesh is static or kinematic, never dynamic, since a pile of triangles has no inside to fall with. Compressed `.glb` files (Draco, meshopt) cannot be read for a collider; export the level uncompressed.

`world.heightfield` is ground as a grid of heights: a terrain chunk. `at` is the grid's corner, where `heights[0]` is, and heights are metres above it, x fastest, so the height at sample `(ix, iz)` is `heights[ix + iz * samplesAlongX]`: the order a mesh grid is laid out in. A square grid needs nothing more; give `samples: [alongX, alongZ]` for one that is not. It is the same ground the triangles of that grid would make with `world.mesh`, to a ray, a character and `world.nav` alike, and it is made at once and costs much less: a 64 m chunk on a 2 m grid takes 0.05 ms against 0.4 ms as a mesh. A heightfield is static. Ground that changes, flattened under a building, is a new one: `destroy()` the old.

## A character

```tsx
const me = world.character({ at: [0, 0, 0], actor: scene.spawn(hero) })

useFrame(() => {
    const stick = input.keyboard.wasd()
    me.walk([stick.x * 5, 0, stick.y * 5])
    if (me.grounded && input.keyboard.wasKeyPressed("Space")) me.jump(1.2)
})
```

A character is what a player or an enemy walks with. `walk` takes the speed it wants, in metres a second, and holds it until you change it: every step it slides along walls, climbs ledges up to `stepHeight` (0.4 by default, a kerb), will not walk up slopes steeper than `slope` (45 degrees), falls when nothing is under it, and keeps to the ground over a crest. `walk([0, 0, 0])` stops it.

`walk` moves along the ground: an up or down in it is ignored, since those are a jump's and gravity's. `jump(height)` leaps that many metres high against the world's gravity; call it while `me.grounded`. `me.velocity` is how it actually moved over the last step, its fall included, and `me.position` is where its feet are. `me.teleport(at)` puts its feet exactly there.

A character pushes nothing and nothing pushes it: walking into a crate stops it, as a wall would. To knock one back, `me.addVelocity([0, 4, 6])`: the up part throws it as a jump does, and the rest shoves it along the ground beside its walk, carrying on in the air and fading out in about a fifth of a second once it lands. Two characters bump into each other too; `ignores: ["player"]` walks it through everything on the `player` [layer](#layers).

A networked cart usually owns its players' positions rather than keeping a body for each. `world.slide(from, delta)` is a character's move without a character: feet at `from`, moved by `delta` metres, sliding and climbing as `walk` would, and it answers `{ at, grounded }`.

## A car

```tsx
const car = world.car({ at: [0, 1, 0], actor: scene.spawn(body), wheels: [scene.spawn(wheel), scene.spawn(wheel), scene.spawn(wheel), scene.spawn(wheel)] })

useFrame(() => {
    const keys = input.keyboard.wasd()
    car.drive(keys.y, keys.x, input.keyboard.isKeyDown("Space") ? 1 : 0)
})
```

`world.car` is a car that drives itself from what you hold with `drive(throttle, steer, brake)`: throttle and steer from -1 to 1 (steer 1 turns right; throttle -1 brakes and then reverses), brake from 0 to 1. What you give it holds until the next call, so call it once a frame from the keys or a stick, and after `drive(0, 0)` it rolls to a stop. A stick's `y` is -1 at the top, the way the stage counts, so a stick drives with `car.drive(-stick.y, stick.x)`. A car held still on a slope stays where it is.

Every number has a default, a small car at a cart's pace: `size` [1.8, 0.5, 4] metres (width, height, length), `mass` 1200 kg, `wheelRadius` 0.35, `topSpeed` 30 metres a second, `acceleration` 4 (the seconds to near top speed), `steering` 40 (the wheels' lock in degrees at a crawl, narrower at speed), `grip` 1 (lower slides, higher corners harder) and `drivenWheels` `"rear"`, `"front"` or `"all"`.

`actor` is the body's model, centred on it. `wheels` are four models, front left, front right, rear left and rear right, which the world places where each wheel is, steered and rolling. Without them, `car.wheels` says where each one is, to place your own. `car.speed` is metres a second forward, negative in reverse, and `car.grounded` is whether any wheel touches the ground.

`car.body` is an ordinary body: it hears touches, takes a `push`, and comes back with a rewind. To set an overturned car back on its wheels, lift it and keep only its yaw: `car.body.position = [at[0], 1, at[2]]`, `car.body.rotation = { yaw: car.body.rotation.yaw }` and `car.body.velocity = [0, 0, 0]`, with `at` its position. `car.destroy()` takes it out. A camera behind it is [`useFollowCamera`](/docs/3d#cameras-you-drag)`(car.body.actor, { behind: true, world, camera: scene })`.

## Asking the world

```tsx
const hit = world.raycast(gun, target, { only: ["wall"] })            // first thing on the line, or null
if (world.canSee(eyes, player, { skip: [me] })) chase()
const swing = world.sweep(shape.sphere({ radius: 0.4 }), from, to)    // a shape moved along a line
const near = world.overlap(shape.sphere({ radius: 3 }), blast)         // every body in a radius
const spot = world.clearSpot(shape.capsule(), [0, 0.8, 0])            // nearest place it fits, or null
const seen = world.visibility(me.position, { within: 20, skip: [me] }) // the floor in sight
```

A `Hit` has the `point`, the surface's `normal`, the `distance` along the line and the `body` it met, a character included, as `overlap` lists characters too. A body made this frame is already there for every query above; `slide` and a character's walk meet it from the next step. Triggers are not there at all: a ray passes through a pickup. `canSee` takes a point or a body; a body is looked at in its middle, and does not block the view of itself. A ray that starts inside you meets you first, so give it `skip: [me]`.

`clearSpot` answers where the shape's middle goes. For a character, ask near where its middle would be, then teleport its feet half its height below: `if (spot) me.teleport([spot[0], spot[1] - 0.8, spot[2]])`.

`visibility` is the floor someone standing at a point can see: a polygon round them, out to `within` metres, cast at `height` above their feet (1.5 by default), so anything lower is seen over. It answers what `canSee` would from that height, so whatever is inside it, `canSee` from their eyes agrees. Skip whoever is looking, `skip: [me]`, or the eye starts inside its own body and sees nothing: an eye inside a body answers one corner, there. It answers `{ outline, reaches }`: `outline` is the polygon's corners at that height, anticlockwise seen from above, so a fan of triangles `(eye, outline[i + 1], outline[i])` drawn with `scene.mesh` faces up, and `reaches[i]` is what corner `i` lies on, a body or a character, or `null` where it is the edge of range. Draw it for fog of war or a guard's cone, or darken everything outside it for shadows.

`shape.box({ size })`, `shape.sphere({ radius })` and `shape.capsule({ radius, height })` are shapes as values, in no world. Besides sweeping and overlapping, a shape answers questions about a place and a time that are not now: `shape.raycast(from, to, { at })` against a shape standing somewhere else, `a.overlaps(b, { at, otherAt })`, and `a.firstTouch(b, { velocity, otherVelocity, within })` for when two moving shapes first touch, exactly, which is how a hit is judged where a target was a quarter of a second ago.

## Layers

```tsx
world.box({ at, size, layer: "wall" })
world.raycast(from, to, { only: ["wall"] })
world.overlap(shape.sphere({ radius: 2 }), at, { skip: ["pickup", me] })
world.sphere({ at, radius: 0.1, dynamic: true, layer: "shot", ignores: ["shot"] })
```

A layer is a name you choose, up to 16 in one world. Every query takes `only` (just these layers) and `skip` (never these layers or bodies). Bodies on every layer collide with each other unless one `ignores` the other's layer: shots that pass through each other, players that pass through players.

## Touches and triggers

```tsx
crate.onTouch((other, contact) => { if (contact.speed > 3 && contact.point) thud(contact.point) })

const coin = world.sphere({ at: [3, 1, 0], radius: 0.4, trigger: true })
coin.onEnter((who) => { if (who === me) collect(coin) })
coin.onLeave((who) => {})
```

`onTouch` fires when something starts touching a body, once, not every frame it rests there, and `contact.speed` says how hard: how fast the two were closing, in metres a second. A character hears both what it walks into and what runs into it. `onTouchEnd` fires when they part. A `trigger: true` body never blocks; it reports what comes in with `onEnter` and what leaves with `onLeave`. Each returns a function that unsubscribes. Give a body a `tag` and read it back from `other.tag`.

## Paths

```tsx
const nav = await world.nav({ radius: 0.3, height: 1.6 })
const route = nav.path(bot.position, me.position)                 // corners to walk through
```

`world.nav` builds the walkable floor from every static, solid body as it is now: walls, crates and mesh levels, shrunk by the walker's `radius`, under ceilings at least `height` tall, up ledges to `stepHeight` and slopes to `slope` as a character climbs them. A box standing upright is solid, and so is a sphere's or capsule's bounding box: the floor under one is not floor, so a path goes round a boulder, never into it, and its top is floor if a walker can climb onto it. A mesh is its surface alone, so close it or stand a box in it. From runtime 1.6 both navs, solo and tiled, know this; on 1.5 the solo nav saw only surfaces, and the ground inside a box or boulder taller than the walker came out as floor walled in. `path` gives the corners of the shortest way there, ending at the goal or as near it as can be reached, `[goal]` when you are already there, and an empty list when either end is nowhere near the floor. On 1.5, already there answered an empty list too, which read as no way there. Walk a character from corner to corner with `walk`.

`nav.nearest(point)` is the closest point of the floor, or null when there is none near: give it `within`, in metres, to say how near, so `nav.nearest(p, 0.2) !== null` asks whether p is on the floor, and a click on a wall becomes a goal beside it. `nav.polygons()` is the floor as triangles, for drawing while you tune a level: `scene.mesh({ ...nav.polygons(), color: "#3c8a" })`. Both are runtime 1.6's.

Building takes a few tens of milliseconds for an arena, so do it once when the level is up. A level that changes builds a new one, or use tiles.

### A world that changes

```tsx
const nav = await world.nav({ radius: 0.4, height: 1.8, tile: 16 })
const hall = world.box({ at: [40, 4, 12], size: [20, 8, 20] })    // the nav reroutes round it
hall.destroy()                                                    // and back
const fire = nav.block({ at: [8, 1, 3], size: [3, 2, 3] })        // no way through, with no collider
fire.remove()
nav.mark({ at: [0, 0, 20], size: [4, 1, 60], area: "road" })
const route = nav.path(bot.position, goal, { cost: { road: 0.5 } })
```

From runtime 1.6, with `tile`, the floor is built in squares that many metres across, pinned to the world's origin, and the nav follows the world: a static body made, destroyed or moved marks the tiles it touches as stale, and the world rebuilds them after each frame, a tile at a time, for up to `budget` milliseconds (1 by default). So a building's collider and the way round it are one call, and a world that streams in chunks keeps its paths as chunks come and go. Pick tiles that divide your chunks: 16 m tiles in 64 m chunks. The cell bends a little so a whole number fit a tile. `budget: 0` leaves the rebuilding to you: `nav.update(ms)` rebuilds for that long, at least one tile, and returns how many are still stale, which is also `nav.pending`.

`nav.block` keeps walkers out of a box where there is no collider, a fire or a cordon, and `nav.mark` names the floor in a box, a road or mud. `path` then takes `cost`, what a metre of each area costs against 1 for plain floor, and `avoid`, areas it never crosses. Both boxes take `yaw` in degrees, and both return a handle whose `remove()` takes them away. They rebuild their tiles as a collider does.

For PrimoEden's terrain (64 m chunks on a 2 m grid, rolling hills, a walker 0.4 m round on 0.33 m cells, 16 m tiles), a tile builds in about 0.4 ms. A 3 by 3 chunk world is 144 tiles and about 80 KB of navmesh, and a path across it, 255 m, takes 0.02 ms. A 20 by 20 m hall going up reroutes in two frames at a 2 ms budget, where one solo navmesh over the same world takes 270 ms to build again.

## Rewind

```tsx
const saved = world.snapshot()
// ...
world.restore(saved)
```

`snapshot` is every body's state as bytes; `restore` puts every body back where it was, a character mid-jump and a gliding lift included. A body made since is destroyed, its actor with it, and one destroyed since comes back, behind the handle you already hold, without the actor that went with it. The simulation is deterministic: on one version of oj, the same steps from the same snapshot land the same way on every browser and every machine.

## Stepping it yourself

`createWorld()` is the same world without the hook: `await createWorld()`, then call `world.step()` from your own loop and `dispose()` when done. It is for a world that outlives a component, or one in a room script, which has no scene; everything on this page works there except actors. The world steps 60 times a second whatever the frame rate; `createWorld({ rate: 30, gravity: [0, -20, 0] })` changes either.

## On the 2D stage

```tsx
import { useEffect, useRef } from "react"
import { mount, useStage, useWorld2D, View } from "oj"

function Pile() {
    const stage = useStage()
    const world = useWorld2D()
    const ball = useRef(null)

    useEffect(() => {
        if (!world) return
        world.box({ at: [stage.width / 2, stage.height + 50], size: [stage.width, 100] })   // the floor
        world.circle({ at: [stage.width / 2, 0], radius: 30, dynamic: true, bounce: 0.6, actor: ball })
    }, [world])

    return <View ref={ball} style={{ position: "absolute", width: 60, height: 60, borderRadius: 30, backgroundColor: "#f4a" }} />
}

mount(<Pile />)
```

`useWorld2D()` is everything on this page but the car, in stage pixels with y down and degrees clockwise, the stage's own units. Its actors are elements, or refs to them: the world puts each one's centre on its body's centre, or on a character's middle, and turns it with the body, so give it `position: "absolute"` in a parent at the stage's top left. Destroying a body leaves its element alone, since React owns it, and a rewind that brings the body back carries it again.

Its bodies are `box`, `circle` and `capsule`, `polygon({ points })` for any convex outline, and `outline({ points, closed })`, a line through points for ground, walls and a level of any shape, which is static or kinematic as a mesh is. `shape2D` makes the first three as values. A character walks along the stage's x, with up being up the screen, so `me.walk([stick.x * 300, 0])` and `me.jump(120)` work as they read.

Gravity is `[0, 980]` by default: down the screen, at a metre's g when a metre is 100 pixels. `useWorld2D({ pixelsPerMeter: 50 })` changes that scale, which is what mass, density and the engine's sense of size are measured in: at 100, a 100 px crate is a 1 m crate. A crate that size weighs 500 kg, so throw things with `addVelocity`, in pixels a second, rather than `push`. A top-down cart wants `gravity: [0, 0]`: with no gravity a character walks every way, and `visibility` is what a viewer sees across the stage, from the point it is given, with no `height`. A character on the stage is upright, 60 pixels wide and 160 tall unless told otherwise, its `position` at its feet; seen from above give it `height` twice its `radius`, `world.character({ at, radius: 18, height: 36 })`, so it is round and its feet are its middle.

Paths on the stage are for such a world seen from above: `await world.nav({ radius: 30 })` makes every static body a wall, with the floor the box round them all, and `nav.path(from, to)` answers the corners in pixels, as in 3D. `radius` is the walker's, in pixels; `cell`, a third of it by default, is how finely the floor is measured, and smaller is more exact and slower to build. `only: ["wall"]` counts only those layers as walls.
