# physics

Part of the [scripting reference](index.md), written by the engine so it matches your `frost`. Start with [your first game](../start/first-game.md) if you are new.

Use when making a player jump, move or collide, adding bodies or sensors, casting rays or pushing objects in 2D or 3D.

With a `[physics]` table a 3D game has Jolt's physics, the same everywhere. `Body`
gains `vz` and `spin_x`, `spin_y`, `spin_z` (degrees a second); `Collider.shape` is
`"box"`, `"sphere"`, `"capsule"` or `"cylinder"` (upright), with depth `d`, or `"ground"`:
the height field of the thing's own `Ground`, which never moves (E1102 otherwise). Physics
writes `x`, `y`, `z` and the turn, never the scale, which a `Collider`'s size is
multiplied by (see Scale, under Physics). Units are metres; gravity defaults
to `[0, -9.81, 0]`. Events are 2D's. `physics.ray(x1, y1, z1, x2, y2, z2, mask?,
ignore?)` answers `{ entity, x, y, z, nx, ny, nz, fraction }` or nil, as in 2D, and
`physics.ground(mover)` too. `physics.cast(x, y, z, w, h, d, dx, dy, dz, mask?, ignore?)`
answers so for the unturned box moved by `dx, dy, dz`, and `physics.overlap(x, y, z, w,
h, d, mask?, ignore?)` lists what touches it, in slot order. `physics.mass(entity)`: a
cube of a metre at `density` 1 weighs 1. `physics.impulse(entity, x, y, z, px?, py?, pz?)`
and `physics.force` push as in 2D, a force for the fixed step's length (kept up, bit for
bit an impulse of `x * dt` each step); off the middle they turn it right-handed: that cube
pushed up by 1 half a metre right of its middle gets `spin_z` 171.9. A `Joint` is 2D's,
with `z`, `to_z` and a hinge's or slider's `axis_x`, `axis_y`, `axis_z` (made one long;
all 0 is 2D's z, or `angle` for a slider; given, it wins over `angle`). `"ball"` turns
every way, with no limits yet; `"wheel"`, a weld's `spring` and a distance joint's `power`
are refused at load. A `Vehicle` is a car: see Physics.

A `Mover` walks as in 2D, with `vz`; `drop` is refused. Movers walk before the bodies:
one standing on a body is carried by it, up, down and across, stays on it when it stops,
and goes round a turning one unturned. Two movers pass through each other; a dynamic body
pushes one as in 2D; it sends no `contact` (a sensor sees it). A capsule or place a script writes is the mover's from that step; a
capsule with no room is refused.

## Physics

An entity with a `Transform` and a `Collider` is in the simulation. What moves it is
decided by what else it has: nothing (it never moves: ground, walls), a `Body` (the
simulation moves it), or a `Mover` (a script walks it: a character). A `TileCollider`
on a tilemap's entity makes its tiles solid, and a `Joint` joins a body to another. Each fixed step runs physics first, then the
scripts, so a script reads where the step left things and what touched in it.

| Component | Field | Type | Default | Meaning |
| --- | --- | --- | --- | --- |
| `Body` | `kind` | text | `"dynamic"` | `"dynamic"`: moved by gravity and by what it hits. `"kinematic"`: moves by its own `vx`, `vy` and `spin`, and nothing pushes it back (a lift, a paddle). `"static"`: never moves |
| `Body` | `vx` | number | 0 | Velocity to the right, in units a second. Read it, or write it to throw the body |
| `Body` | `vy` | number | 0 | Velocity upwards |
| `Body` | `spin` | number | 0 | How fast it turns, in degrees a second, anticlockwise |
| `Body` | `gravity` | number | 1 | How much of the project's gravity pulls on it: 0 floats, 2 falls twice as hard |
| `Body` | `damping` | number | 0 | How quickly it loses speed to nothing in particular, like air. 0 never |
| `Body` | `fixed` | true or false | false | It never turns: a crate that slides but does not tumble |
| `Body` | `bullet` | true or false | false | Checked along its whole path against bodies that move: for a shot, which could pass through a thin crate between two steps. Static colliders stop everything either way |
| `Collider` | `shape` | text | `"box"` | `"box"`, `"circle"`, `"capsule"` or `"polygon"`, centred on `Transform` |
| `Collider` | `w` | number | 16 | Width in units, times the thing's scale (see Scale, below). A circle's diameter |
| `Collider` | `h` | number | 16 | Height. A capsule taller than wide stands up; wider than tall lies down. Not used by a circle |
| `Collider` | `points` | text | `""` | A polygon's corners about `Transform`, as `"x,y x,y x,y"`: 3 to 8, convex |
| `Collider` | `sensor` | true or false | false | It stops nothing and reports what is inside it |
| `Collider` | `senses` | text | `"moving"` | What a sensor reports. `"moving"`: dynamic and kinematic bodies and movers. `"all"`: static colliders and tilemaps too, so one on a floor reports the floor in its first step |
| `Collider` | `one_way` | true or false | false | A platform a `Mover` jumps up through and lands on. Other bodies meet it as solid |
| `Collider` | `layer` | whole number | 1 | Which of 16 layers it is on, as a bit: 1, 2, 4, 8 and so on up to 32768 |
| `Collider` | `mask` | whole number | 65535 | The layers it meets, as bits added together. Two colliders meet when each is on a layer the other's mask has |
| `Collider` | `friction` | number | 0.6 | 0 is ice |
| `Collider` | `bounce` | number | 0 | 1 keeps all its speed in a bounce |
| `Collider` | `density` | number | 1 | Mass for its size: a body of twice the density is twice as hard to push |
| `Collider` | `surface` | number | 0 | A belt: the speed its surface runs at, clockwise round it, so its top goes right. Bodies and movers on it are taken along |
| `TileCollider` | `solid` | text | `""` | The characters of the tilemap's `rows` that are solid |
| `TileCollider` | `one_way` | text | `""` | The characters that are one-way platforms, solid along their top |
| `TileCollider` | `layer` | whole number | 1 | As `Collider.layer`, for every tile |
| `TileCollider` | `mask` | whole number | 65535 | As `Collider.mask` |
| `TileCollider` | `friction` | number | 0.6 | As `Collider.friction` |
| `TileCollider` | `bounce` | number | 0 | As `Collider.bounce` |
| `Mover` | `vx` | number | 0 | The velocity the script wants this step. After the step: what was left of it (0 against a wall) |
| `Mover` | `vy` | number | 0 | The same upwards. The script adds its own gravity and jump |
| `Mover` | `grounded` | true or false | false | Written by the engine: it stands on something |
| `Mover` | `crushed` | true or false | false | Written by the engine every step, with or without a script: true while a kinematic body squeezes it against what does not give (a lift under a ceiling, a ram against a wall) or is inside it, false once it is free. Nothing moves it out: that is the script's. Never from dynamic bodies |
| `Mover` | `slope` | number | 50 | The steepest ground it walks on, in degrees. Steeper is a wall |
| `Mover` | `step` | number | 0 | The highest ledge it walks up, and kerb it walks down, without leaving the ground: stairs |
| `Mover` | `air` | number | 0 | Written by the engine: the seconds since it last stood. 0 on the ground |
| `Mover` | `push` | number | 1 | How hard it shoves dynamic bodies in its way, as a density. 0: they stop it like walls |
| `Mover` | `mass` | number | 1 | Its weight on the dynamic body it stands on, as a density: at 1, what a body of its capsule and a `density` of 1 weighs. 0: none |
| `Mover` | `drop` | true or false | false | While true it falls through one-way platforms |

| In a script | Does |
| --- | --- |
| `physics.ray(x1, y1, x2, y2, mask?, ignore?)` | The first collider on the line from the first point to the second: `{ entity, x, y, nx, ny, fraction }` (where, the surface's direction there, and how far along the line from 0 to 1), or nil |
| `physics.cast(x, y, w, h, dx, dy, mask?, ignore?)` | The first collider the box centred on `x, y` meets when moved by `dx, dy`: the same answer as a ray, with `x, y` where they touch and `fraction` how much of the move it made first (0 when it touches something where it starts), or nil |
| `physics.overlap(x, y, w, h, mask?, ignore?)` | A list of the entities whose colliders touch the box centred on `x, y` |
| `physics.ground(mover)` | The entity a `Mover` stood on at the end of the last physics step, or nil in the air |
| `physics.mass(entity)` | The mass of an entity's dynamic body, or nil when it has none. A box 32 by 32 with a `density` of 1 has a mass of 1 |
| `physics.impulse(entity, x, y, px?, py?)` | Pushes a dynamic body once: its velocity changes by `x, y` divided by its mass. Made at the point `px, py` of the world it turns the body too. False for an entity with no dynamic body |
| `physics.force(entity, x, y, px?, py?)` | The same for a push kept up: call it every step it lasts. An impulse of `x, y` times the step's length |
| `physics.pause(on)`, `physics.paused()` | Holds the simulation or lets it go on, and whether it is held |

- **Units.** Sizes and places are world units, the same as what is drawn; angles are
  degrees. `[physics]` in the project file sets gravity (980 units a second squared
  downwards when left out), how many units are a metre to the simulation (32) and the
  solver's sub-steps (4). The simulation is tuned for moving things between a tenth of
  a metre and ten metres across: 3 to 320 units at 32 to the metre. For a game of small
  pixels, lower `unit`.

- **What is written.** After each step a body's `Transform`, `Body.vx`, `vy` and `spin`
  hold where it is and how it moves, and a body that has turned is given a `Rotation`.
  Writing `Transform` or `Rotation` puts the body there; writing the velocity sets it.
  Changing a `Collider` or `Body.kind` makes the body again with the new shape.

- **Scale.** A collider's shape is its written size times its thing's scale in the
  world: its own (`Scale` in 2D; `sx`, `sy`, `sz` in 3D) times that of each parent that
  has a `Transform`. A box and a polygon take any scale. A circle, a sphere and a
  capsule take only one that is alike along every axis, and a cylinder one alike along
  x and z; any other, and a scale of 0, is `E0471`: at the load, at the step after a
  script wrote it, and at a `world.set`, which then changes nothing. Below 0 mirrors: a
  polygon's corners are mirrored and the other shapes are as they were. A
  `TileCollider` grows with its tiles from the map's corner, by scales above 0 only. A
  changed scale makes the body again where it is, moving as it moved: `density` stays,
  so its mass follows its area (in 3D its volume), and what touched it sends
  `contact_end`, then `contact` again. So to pop or squash a picture, scale a thing
  under the one that has the `Collider`, not that one. A `Mover`'s capsule is scaled,
  its speeds and `step` are not; a `Vehicle`'s body is, its wheels are not.

- **Pushing a body.** `physics.impulse` and `physics.force` add to `Body.vx`, `vy` and
  `spin` at once, by the mass the last physics step knew, so they are recorded like any
  write. A body spawned this step is pushed from the next. A force of
  `physics.mass(entity) * 980` upwards holds a body up against gravity.

- **Pausing.** After `physics.pause(true)` no body or mover moves and no event is sent
  until `physics.pause(false)`; scripts, the interface and tweens go on, for a menu over
  a game that holds still. Bodies go on with the speed they had. What a script spawns,
  moves or despawns meanwhile is still seen by questions. The pause is in the checksum
  and the recording, and outlasts `scene.load`.

- **Static.** A `Collider` with no `Body` is static. Moving its `Transform` moves it,
  but it carries and pushes nothing on the way: for a platform that moves, use a
  kinematic `Body` and set its velocity.

- **Layers.** `mask` in a question is the layers to look at; left out, all. Sensors are
  never returned by a question. One-way platforms and movers are.

- **Ignoring the one that asks.** A ray or a cast that starts inside a collider meets
  it first, at `fraction` 0. `ignore` is one entity whose colliders the question passes
  over: `physics.ray(x, y, x, y - 40, nil, hero)` is the ground under `hero`.

- **When questions are answered.** `physics.ray`, `physics.cast` and `physics.overlap` see the bodies
  as the physics step left them: what a script moves or spawns is seen from the next
  step, and what it has despawned is left out. In `on_scene` they see nothing of the scene
  that is starting: its bodies are made when every `on_scene` has run, so a ray asked
  there meets none of its walls. Ask from the first step on (a camera kept out of walls is
  a `Follow`, which the engine places against the new walls before the first picture).

- **More.** `docs/physics.md`: how stiff stacks and joints are, how long a chain swings,
  belts, ledges, and a jump that forgives.

- **Mistakes.** A collider that cannot be made (`E1101` to `E1108` and `E1113`: an
  unknown shape or kind, a size of 0, a polygon that is not 3 to 8 corners or not convex, a layer
  outside 16 bits, a `Mover` whose collider is not an upright capsule or that also has
  a `Body`, a `TileCollider` without a `Tilemap`, a `senses` that is neither word) or a
  joint that cannot (`E1110`, `E1111`) stops the load or the step with the entity's
  name and what to write. A joint between two things that never move is made, with a
  warning (`W1114`).

### A character

A `Mover` is a character that goes where the script says and is stopped by what is
solid. It needs a `Collider` that is a capsule taller than wide, and no `Body`. Each
step the script writes the velocity it wants; the engine slides it along walls and
ground, keeps its full speed up and down slopes no steeper than `slope`, lands it on
one-way platforms, and says whether it stands. Gravity and jumping are the script's:

```luau
function step(dt)
    local hero = find("hero")
    local vy = get(hero, "Mover", "vy")
    if get(hero, "Mover", "grounded") then
        vy = if input.held(0, "jump") then 400 else 0
    else
        vy = math.max(vy - 1200 * dt, -600)
    end
    set(hero, "Mover", "vx", input.get(0, "move") * 110)
    set(hero, "Mover", "vy", vy)
    set(hero, "Mover", "drop", input.held(0, "down"))
end
```

```toml
[hero]
Transform = { x = 40, y = 44 }
Collider = { shape = "capsule", w = 12, h = 24 }
Mover = {}

[level]
Transform = { x = 0, y = 0 }
TileCollider = { solid = "#", one_way = "-" }

[level.Tilemap]
image = "tiles.png"
legend = "#-"
rows = """
........
..---...
########
"""
```

Solid tiles that touch are joined into one outline, so a mover or a rolling body does
not catch on the seams between tiles. A mover held up by dynamic bodies on both sides
with nothing under its feet counts as standing, so it can jump out. It pushes dynamic
bodies and is seen by sensors (`sensor_enter` with the mover as `other`); it sends no
`contact` events: ask `physics.overlap` what is around it. To a question it is a
collider like any other: a ray from inside the mover meets the mover, so give it as
`ignore`.

Standing, its feet are exactly on the ground (a capsule 24 high on a floor whose top
is at 16 is at 28), and `physics.ground(mover)` is that ground. A body it stands on
carries it, across, up and down, and round as it turns, on top of its own move; the
capsule stays upright. A kinematic body carries it exactly; a dynamic one by the speed
it has, above 1.6 units a second. On a dynamic body it has weight, `Mover.mass`: a
seesaw goes down and a rope bridge sags as under a body of its size.

Nothing takes a mover through a static collider, whatever pushes it. A dynamic body
pushes a mover that is free to go. Where it cannot go (a floor or a wall is behind it,
or it stands on something) the body is stopped as by a wall: a crate that falls on its
head lies there, and falls when the mover walks from under it. So `crushed` comes from
kinematic bodies only. A limit: a body deeper in the capsule than half its width is
not put out; that takes one made there, or one faster than two capsule widths a step.
the engine's `physics` example is a whole game with all of this: 200 crates, a character, two
sensors, a ray and an overlap.

```toml
# Optional: physics. `gravity` pulls on dynamic bodies, in units a second squared;
# `unit` is how many world units are a metre to the simulation, 1 or more (lower it
# for a game of small pixels); `substeps` is how many smaller steps the solver takes in
# one fixed step, 1 to 16 (more is stiffer and slower). Left out: as written here.
# A game has the physics when it has this table (empty will do) or a scene gives an
# entity one of its components. One whose scripts alone make colliders needs the table.
# A 3D game's may say `threads`, 0 to 16 (left out: 0): how many worker threads a step's
# physics runs on beside the stepping thread, the same bits on any number. A machine with
# fewer cores runs on its cores less one, and `frost check` says so; a web page runs on
# the stepping thread. Workers slow a small game and speed up only thousands of awake
# bodies: measure with the `workers` example of frost_physics.
[physics]
gravity = [0, -980]
unit = 32
substeps = 4
```
