# carry
> In a world that installs the Controllers library (`world.installLibrary({ world = "034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" })`), every package name on this page is written with `@controllers::` in front of it, and `asset.list("component")` lists each one under that name.
The colliders a character carries: the one on its own entity and the ones
on every entity parented under it, such as a held prop, a weapon or a
trigger volume that travels with the character. A carried collider moves
with the body, so it is never ground the body stands on, a ceiling it
bumps, or a wall it walks into. The ground, ceiling and wall passes of the
character controller all ask their questions through this module. No
state.
## Exports
- `M.carriedBy(entityId: string, selfId: string) -> boolean`:
whether the collider on `entityId` is one the body `selfId` carries:
`selfId` itself or an entity parented under it at any depth. An empty
`selfId` carries nothing.
- `M.raycast(origin: Vec3, dir: Vec3, maxDist: number, selfId: string) -> hit?`:
cast a ray and return the first surface it meets that the body does not
carry, passing through every carried collider on the way. Returns the
raycast hit table `{ entityId, point, normal, distance, startedInside }`
or `nil`.
## Usage
```luau
local Carry = require("characterController.characterController.physics.carry")
-- The ground under a character, whatever it holds at its feet.
local hit = Carry.raycast({ x = px, y = py + 0.3, z = pz }, { x = 0, y = -1, z = 0 }, 0.5, selfId)
-- A sweep that skips what the body carries.
if not Carry.carriedBy(sweepHit.entityId, selfId) then
-- a wall
end
```
# ceiling
> In a world that installs the Controllers library (`world.installLibrary({ world = "034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" })`), every package name on this page is written with `@controllers::` in front of it, and `asset.list("component")` lists each one under that name.
Single-ray ceiling-detection helper for the character controller.
Casts upward from the character's head to detect overhead obstacles
(head bonk, low clearance). No state.
## Exports
- `M.cast(x: number, y: number, z: number, height: number, skinWidth: number, selfId: string) -> hit?` —
cast a ray from `(x, y + height - skinWidth, z)` upward for
`skinWidth * 2`. Returns the raycast hit table or `nil`. The ray passes
through the colliders the body carries (`selfId` and every entity
parented under it), so a prop held overhead is never a ceiling.
## Usage
```luau
local Ceiling = require("characterController.characterController.physics.ceiling")
local hit = Ceiling.cast(px, py, pz, 1.8, 0.01, selfId)
if hit then
-- head bonk: zero out upward velocity
end
```
## Notes
- Pure function — no module state, no side effects beyond the engine
raycast itself.
- The ray is intentionally short (`skinWidth * 2`) so a head-bonk
check only fires when the character is actively pressing up
against a ceiling, not when there is ambient overhead geometry
far above.
# characters
> In a world that installs the Controllers library (`world.installLibrary({ world = "034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" })`), every package name on this page is written with `@controllers::` in front of it, and `asset.list("component")` lists each one under that name.
The bodies characters meet one another as. A `CharacterController` moves by
sweeping its capsule against colliders, and this module stands every other
character in those sweeps' way. Every entity carrying a `CharacterController` is an
upright capsule standing on its feet, `radius` round and `height` tall, where
its entity stands, and the wall pass (`physics.walls`) sweeps against those
capsules beside the colliders: a character walking into another stops a skin
short of it, slides the rest of its walk around it, and reads `blocked` when
the other refuses the walk.
## The push rule
- A walk never moves another character. Each character moves itself alone,
so the bodies meet the same way on every peer: each peer moves the
characters it owns against where it sees the others, a remote player's
body among them.
- Two characters that overlap (placed into one another, a body the network
shows a frame late, two spawned at one point) move apart at no more than
the speed the controller gives (`apart`), each taking half the overlap. A
pair pressed together rests a skin apart; an overlapped pair comes apart
over a few frames without either being thrown, and never through a wall.
- A character gives way to no body moving into it. That body is the one to
stop, by its own sweep on the peer that moves it, so a player walking into
a standing one never drives it along, however late each peer sees the
other.
- Two characters at the very same point come apart along the frame's X, the
one whose entity id sorts first towards +X, which every peer reads alike.
- Only bodies that share some height meet: a character jumping over another
passes above it, and a character coming down onto another's head is moved
off it to the side.
## Who meets whom
Each character carries a `contactTag` (`"character"` by default). Two
characters whose tags the world's contact filter answers `"ignore"` or
`"sensor"` pass through each other:
```luau
Physics.setContactFilter("character", "character", "ignore") -- nobody blocks anybody
entity(ghostId).component.get("CharacterController").contactTag = "ghost"
Physics.setContactFilter("ghost", "character", "ignore") -- the ghost walks through people
Physics.setContactFilter("redTeam", "redTeam", "ignore") -- teammates pass, foes block
```
A character never meets itself, a character parented under it, or one it is
parented under.
A character is a body while its entity is active and its `CharacterController`
enabled: one whose entity is set inactive (`entity(id):setActive(false)`) or
whose controller is disabled (`controller.enabled = false`) stands in nobody's
way until it is switched back on.
## Exports
- `M.DEFAULT_TAG`: `"character"`, the tag a character meets others by when
content names no other.
- `M.passes(tagA: string, tagB: string) -> boolean`: whether the contact
filter lets two characters with those tags pass through each other.
- `M.near(x, y, z, reach, radius, selfId, frame?) -> { Body }`: the other
characters within `reach` of touching the character `selfId`, with their
feet, capsule and tag, as one read a step's sweeps share. Every
character's body is read from its entity once a frame.
- `M.placed(selfId, x, y, z)`: states where a character put its feet once
it has moved itself. The bodies are read once a frame; the characters
moving after it in the same frame meet it where it now stands.
- `M.sweep(near, x, y, z, dirX, dirZ, distance, height, radius, frame?, bottom?) -> hit?`:
the first character in `near` the body's sweep along `(dirX, dirZ)`
reaches within `distance`, as a hit table `{ entityId, point, normal,
distance, startedInside, character = true }`. A character the body
overlaps already stands in the way only of a walk further into it.
- `M.apart(x, y, z, height, radius, selfId, maxStep, frame?, near?) -> (stepX, stepZ)`:
the step across the frame, at most `maxStep` long, that moves the
character half of each overlap away from the characters it overlaps.
## Usage
```luau
local Characters = require("characterController.characterController.physics.characters")
local near = Characters.near(px, py, pz, 0.5, 0.3, selfId)
local hit = Characters.sweep(near, px, py, pz, 1, 0, 0.5, 1.8, 0.3)
if hit then print("walks into", hit.entityId, "after", hit.distance) end
```
# ground
> In a world that installs the Controllers library (`world.installLibrary({ world = "034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" })`), every package name on this page is written with `@controllers::` in front of it, and `asset.list("component")` lists each one under that name.
Ground-probing and slope-math helpers for the character controller.
A downward raycast helper plus two pure vector helpers (slope angle,
plane projection). No state.
## Exports
- `M.cast(x: number, y: number, z: number, skinWidth: number, maxDist: number, selfId: string, riseDist: number?) -> hit?` —
cast a ray downward from `(x, y + riseDist + skinWidth, z)`, reaching
`maxDist` below the feet. The returned hit's `distance` is adjusted to
be relative to the feet, not the ray origin, and is negative for
ground standing above them. The ray passes through the colliders the
body carries (`selfId` and every entity parented under it), so a prop
held at the feet is never the ground.
- `M.support(x: number, y: number, z: number, radius: number, skinWidth: number, maxDist: number, selfId: string, riseDist: number?, maxSlopeAngle: number?, frame: Frame?) -> hit?` —
the ground the body's footprint stands on: the surface under its centre
(`cast`), or a walkable surface under the rest of the disc of `radius`
around the centre where that stands higher than the centre's ground
continued out to it. A body whose front has stepped over the edge of a
stair stands on that stair, and one walking off a ledge stands on the
ledge until the last of its footprint leaves it. A hit from under the
footprint carries `edge = true` and the surface's own normal.
- `M.slopeAngle(nx: number, ny: number, nz: number) -> number` —
degrees between the supplied normal and world up. Returns 0 on a
zero-length normal.
- `M.projectOnSlope(moveX, moveY, moveZ, normalX, normalY, normalZ) -> (number, number, number)` —
project a movement vector onto the plane perpendicular to a normal:
`v - (v . n) * n`.
## Usage
```luau
local Ground = require("characterController.characterController.physics.ground")
local hit = Ground.cast(px, py, pz, 0.01, 0.2, selfId)
if hit then
local angle = Ground.slopeAngle(hit.normal.x, hit.normal.y, hit.normal.z)
if angle <= 45 then
-- walkable
end
end
local px, py, pz = Ground.projectOnSlope(dx, 0, dz, nx, ny, nz)
```
## Notes
- `cast` shifts the origin up by `skinWidth` to avoid starting the ray
inside the ground when the character is sitting on a contact, then
subtracts `skinWidth` back off `hit.distance` so callers see the
true distance from the feet.
- `riseDist` raises the origin further, so the ray also covers ground
that stands above the feet — the ground a walking character climbs
into. A hit up there reports a negative `distance`: how far the
character rises to stand on it.
- `slopeAngle` clamps `cos(angle)` into `[-1, 1]` before `acos` —
callers don't need to normalise the input.
- `projectOnSlope` does not normalise the surface normal; callers
should pass a unit normal (raycast normals already are).
# platform
> In a world that installs the Controllers library (`world.installLibrary({ world = "034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" })`), every package name on this page is written with `@controllers::` in front of it, and `asset.list("component")` lists each one under that name.
The body a character stands on, and how that body moves the character. A
character standing on a body that moves or turns (a lift, a moving platform,
a turntable, a raft, a ship's deck) is carried with it: the point under its
feet goes where the body takes it, and it turns with the body's turn about
up. Kinematic bodies a script moves, dynamic bodies the simulation moves and
transforms something animates carry it alike. In a multiplayer session a
character states its pose relative to the moving body it rides (`stateFrame`),
so every peer draws it on that body where that peer draws the body.
Poses are read where the frame draws them (`Physics.drawnPose`), so a
character carried by them stays in step with the platform on screen at any
frame rate and physics tick rate. A ride keeps how fast its body moved the
feet on each frame of its last tenth of a second, and of at least its last
six frames (`trail`): averaged, that is
how fast a kinematic body or an animated transform was carrying the character
when it leaves.
## Exports
- `M.pose(entityId) -> (x, y, z, rotation)?` — where an entity is drawn this
frame and how it is turned, in world space.
- `M.hold(entityId, from?, carry?, dt?) -> Ride?` — the body a character
stands on with the pose it is drawn at now. Hold it after the character is
placed each frame; passing the ride the frame began on (`from`), its
`carry` and the frame's `dt` keeps the ride's trail going on the same body.
- `M.carry(ride, x, y, z, up, dt?) -> Carry?` — how that body moved the point
`(x, y, z)` since the ride was held, and how fast it moves it this frame:
`{ entityId, dx, dy, dz, turn, moved, vx, vy, vz }`, `turn` the body's turn
about `up` as a quaternion, `v` the simulation's velocity for the body at the
point (linear plus spin), or the displacement over `dt` for an entity under
no body. nil with no ride or when its body is gone.
- `M.velocityAt(ride, carry, dt) -> (vx, vy, vz)` — how fast the body moves
the feet: a dynamic body's velocity there this frame, else the velocity
averaged over the ride's trail, this frame's `carry` included. What a character keeps as momentum when it leaves the body.
- `M.steer(vx, vz, walkX, walkZ, lerp, keptX, keptZ) -> (vx, vz)` — air
control for a character carrying the motion it kept from a body it left: the
velocity steers toward that motion plus the walk asked for, so with no walk
asked it goes on moving with the body it left.
- `M.keptPast(keptX, keptZ, vx, vz) -> (keptX, keptZ)` — the part of a kept
motion a wall leaves once it cut the step to the velocity `(vx, vz)`: none
for a wall met head on, the part along a wall slid along.
- `M.drawnRise(hit, up) -> number` — how far along `up` the surface a cast met
stands drawn above the point the cast met it at; `Ground.cast` measures the
ground's distance to the drawn surface with it.
- `M.turned(turn, r) -> Quat` — the rotation `r` turned by `turn` in world
space.
- `M.frameOf(entityId?) -> string?` — the entity a character standing on
`entityId` states its pose relative to for the other peers of a
multiplayer session: the entity of the body `entityId` belongs to when that
body is kinematic or dynamic, nil otherwise.
- `M.stateFrame(entityId, frame?, stated?) -> string?` — state the
character's pose relative to `frame` (`multiplayer.setPoseFrame`), or in
the world with nil, when it differs from `stated`; returns the frame stated
now. Every other peer then draws the character where it draws the body it
rides, in step with it.
## Usage
```luau
local Platform = require("characterController.characterController.physics.platform")
-- each frame, before moving the character
local carry = Platform.carry(ride, px, py, pz, up, dt)
if carry then px, py, pz = px + carry.dx, py + carry.dy, pz + carry.dz end
-- ... walk, cast for ground, place the character ...
ride = if grounded then Platform.hold(groundHit.entityId, ride, carry, dt) else nil
-- the frame the other peers of a session draw the character in
stated = Platform.stateFrame(entityId, Platform.frameOf(ride and ride.entityId), stated)
```
# push
> In a world that installs the Controllers library (`world.installLibrary({ world = "034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" })`), every package name on this page is written with `@controllers::` in front of it, and `asset.list("component")` lists each one under that name.
How a character moved by casts pushes the dynamic bodies it walks into. The
wall pass stops the character at a body as at a wall; this gives the body the
push a walker gives it. No state.
## Exports
- `M.into(hit, walkX: number, walkZ: number, pushForce: number, dt: number, frame?) -> number` —
push the dynamic body the walk met (`hit`, a cast hit naming the collider's
entity; `Physics.bodyOf` names the body it rides). Along the way into the
surface the walk met, laid flat across the frame, the push brings the body's
speed up to the part of the walk going into it and no further, with at most
`pushForce * dt` newton-seconds, through the body's centre of mass, so a
crate slides along rather than tipping. Returns the
impulse given: 0 for a hit on no dynamic body, a walk that does not go into
it, or a body already moving away at that speed.
## The model
A body moves when the push is more than what holds it: on level ground a
box of mass `m` sliding with friction coefficient `mu` needs `mu * m * 9.81`
newtons. At the `CharacterController` default of 400 N, a 5 kg crate (about
34 N with the default box friction) and a 40 kg one (about 275 N) are carried
along at the walk, the heavier one taking longer to come up to speed, and a
500 kg one (about 3400 N) does not move: the character stands against it as
against a wall.
## Usage
```luau
local Push = require("characterController.characterController.physics.push")
local step = Walls.move(px, py, pz, vx * dt, vz * dt, 1.8, 0.3, 0.01, 45, selfId, frame)
if step.hit then Push.into(step.hit, vx, vz, 400, dt, frame) end
```
# walls
> In a world that installs the Controllers library (`world.installLibrary({ world = "034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" })`), every package name on this page is written with `@controllers::` in front of it, and `asset.list("component")` lists each one under that name.
Wall-detection and slide helpers for the character controller. Runs the
horizontal pass of a character's step, sweeps the character's own
capsule along the movement direction, puts a body that overlaps a wall
back outside it, probes a single height with a horizontal ray, and
slides a movement vector along a wall normal. No state.
## Exports
- `M.move(x: number, y: number, z: number, dx: number, dz: number, height: number, radius: number, skinWidth: number, maxSlopeAngle: number, selfId: string, frame: Frame?, cameFrom: Point?, stepHeight: number?) -> Step`:
the horizontal pass of one step. Puts a body that overlaps a wall back
outside it (`pushOut`), then carries it along `(dx, dz)`: the body stops
`skinWidth` short of the first wall the step runs into, and the rest of
the step slides along that wall and along the next one the slide meets.
With a `stepHeight`, a wall that cuts the walk short is walked again with
the body lifted by up to that much (as far as `headroom` allows); the
lifted walk is taken when it carries the body further and comes down on
walkable ground above the feet, no higher than a step, clear of every
wall, and the rest of the walk goes on from that step. Returns
`{ dx, dz, pushX, pushZ, overlapped, blocked, hit, stepUp }`: where the
body goes (push included), the push itself, whether the body overlapped a
wall where the step began, whether the step met a wall and gained no
ground towards where it asked to go, the first wall it met, and how far
above the feet the ground it stepped up onto stands.
- `M.headroom(x: number, y: number, z: number, sx: number, sz: number, maxRise: number, height: number, radius: number, skinWidth: number, maxSlopeAngle: number, selfId: string, frame: Frame?) -> number`:
how far the body at the feet `(x, y, z)` moved `(sx, sz)` across the
frame can rise, up to `maxRise`, before its head meets something
overhead.
- `M.pushOut(x: number, y: number, z: number, height: number, radius: number, skinWidth: number, maxSlopeAngle: number, selfId: string, frame: Frame?, cameFrom: Point?) -> (number, number, boolean)`:
the horizontal push that puts a body overlapping a wall back outside it,
`skinWidth` clear of the surface, and whether it overlapped one. The push
runs along the overlap's shortest way out, or back to the side
`cameFrom` stands on when the body's centre has crossed the surface since
it last stood there. `0, 0, false` for a body that overlaps no wall.
- `M.standsAt(placed: Point?, x: number, y: number, z: number) -> boolean`:
whether feet at `(x, y, z)` stand at `placed`, where a mover last put
them, to the precision a position is stored at (a 32-bit float's, which
coarsens with the distance from the origin). A mover keeps its
`cameFrom` only while this holds.
- `M.castBody(x: number, y: number, z: number, dirX: number, dirZ: number, height: number, radius: number, skinWidth: number, maxSlopeAngle: number, selfId: string, distance: number?) -> hit?`:
sweep the capsule spanning the character from the top of the ground
band above `(x, y, z)` (its feet) up to `y + height`, reaching
`distance + skinWidth` past its own surface (`skinWidth` alone when
`distance` is omitted). Returns the wall standing across the path, or
`nil` when the path is clear.
- `M.castDirection(x: number, y: number, z: number, dirX: number, dirZ: number, radius: number, skinWidth: number, selfId: string) -> hit?` —
single horizontal ray of length `radius + skinWidth`, from whichever
sample height the caller passes. The ray passes through the colliders
the body carries (`selfId` and every entity parented under it).
- `M.slideAlongWall(moveX: number, moveZ: number, normalX: number, normalZ: number) -> (number, number)` —
strip the component of `move` going into the wall (`v - (v . n) * n`,
XZ only). Returns input unchanged when `dot >= 0` or the XZ-normal
is effectively zero.
## Usage
```luau
local Walls = require("characterController.characterController.physics.walls")
local step = Walls.move(px, py, pz, vx * dt, vz * dt, 1.8, 0.3, 0.01, 45, selfId)
px, pz = px + step.dx, pz + step.dz
local hit = Walls.castBody(px, py, pz, dirX, dirZ, 1.8, 0.3, 0.01, 45, selfId)
if hit then
local slideX, slideZ = Walls.slideAlongWall(dx, dz, hit.normal.x, hit.normal.z)
end
```
## Notes
- `move` sweeps the whole step, so however long a frame's step is, the
body ends outside every wall it walks at, and the next step it asks for
starts clear of them, away from a wall it rests against as much as
along it.
- A sweep begun inside a wall answers about the overlap in whichever
direction it points. `pushOut` measures how deep the overlap goes by
sweeping the same body back in from one body width outside the wall, so
a body placed inside a wall, or shoved into one, walks again on the next
step. Each push reaches at most that body width, the deepest a body
reaches into a surface: a body overlapping one face of a hollow mesh
collider is put back outside that face, never across the collider at the
face on its far side. A start that lands on another surface of the same
collider, the far wall of a passage one mesh bounds on both sides, comes
in by half until it stands clear, so a body overlapping one wall of a
narrow passage is put back into the passage. A body deeper inside a
solid than its own width comes out a body width at a time.
- A surface has a way out on each side. The shortest is the side the
body's centre stands on, which is the far side once a long step has
carried the centre across a thin surface. A mover passes `cameFrom`,
the feet position of its last step that began with `overlapped` false,
and a body that last stood clear more than a radius behind the shortest
way out is pushed back out the side it came from. The CharacterController
keeps it while the body stands where the controller put it (`standsAt`),
and forgets it once anything else moves the body.
- A collider the body carries, on `selfId` or on an entity parented under
it (a held prop, a trigger volume that travels with the character), is
no wall: `castBody` sweeps through it and `pushOut` pushes nothing out
of it, so a character carrying one stands where it is put and walks.
- Another character is a wall: every entity carrying a
`CharacterController` stands as its upright capsule (`physics.characters`),
so `castBody` and `move` stop a skin short of it and slide around it, and a
hit on one carries `character = true`. `pushOut` pushes nothing out of
another character; a character moves itself apart from one it overlaps
(`Characters.apart`). Two characters the contact filter lets pass, by
their `contactTag`s, are no walls to each other.
- `castBody` sweeps the whole body, so an opening narrower than
`2 * radius` stops the character even when nothing stands on the
centre line — two cabinets 6 cm apart are a wall, not a doorway.
- A contact whose surface faces up or down — the ramps the character
walks up, to `maxSlopeAngle`, and anything directly overhead —
belongs to the ground and ceiling passes. `castBody` runs on up along
a ramp it meets, the way the body climbs it, so a body on a ramp still
reports the wall ahead of it, whether that wall is part of the ramp's
collider or another; it sweeps on past a surface overhead.
- A contact on the rim of a surface (the edge of a stair or a curb), where
the surface under the contact faces another way than the contact does,
stands across the path the way a wall does: `move`'s step pass decides
whether the body climbs it.
- `castBody` starts its sweep above the ground band: a cap of `radius`
resting on ground of angle `a` reaches `radius * (1 / cos(a) - 1)`
below the surface uphill of it, and a sweep begun inside a surface
describes the shortest way out of that overlap instead of the surface
standing across the path. The band is measured at `maxSlopeAngle`, the
steepest ground the character walks, and the ground and step passes own
everything under it.
- `slideAlongWall` normalises the wall normal in XZ; callers don't
need to pre-normalise. The Y component of the normal is ignored
because slide-along is a horizontal operation.
- The slide helper returns the input movement unchanged whenever the
movement isn't pressing into the wall — there's no "stick to wall"
behaviour, only "don't pass through".
# CharacterController
> In a world that installs the Controllers library (`world.installLibrary({ world = "034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" })`), every package name on this page is written with `@controllers::` in front of it, and `asset.list("component")` lists each one under that name.
Kinematic mover. Integrates velocity against gravity, walls, ceilings and
ground, and writes the result to the entity's position every frame.
It is the body's mover: its `.metadata` carries the `bodyMover` tag, which the
velocity verbs (`Physics.setVelocity`, `Physics.addVelocity`,
`Physics.getVelocity`, `Physics.moverOf`), the avatar on the body and a headset
reach it by. A movement component of your own (a vehicle, a hovercraft, a
jetpack) that carries the same tag takes its place on the body, or moves it in
turn with this one: of several movers on one body the enabled one moves it.
The physics guide's "Movers" section (`man topics/physics`) has the contract.
## Driving it
The character moves on a public input bus: `inputX`, `inputZ`,
`inputJump` and `inputJumpHeld`. Each frame the controller reads the bus, moves on what it found,
and then refills it for the next frame.
**Only the local player's body answers the player's controls.** The character
the local player is bound to (`layers.active.players.localPlayer.avatar`)
refills its bus from the `move` axis and the `sprint` / `jump` actions of its
input map, so the map drives it whenever nothing else does. Every other
character holds no map and refills its bus with no movement: an NPC, a
mannequin, a preview or another player's body stands where it is until
something writes its bus. The player's spawn binds the body for you; to hand
the controls to a character you made, bind it:
```luau
layers.active.players.localPlayer.avatar = entity(bodyId)
```
The character takes the map up on the frame after the bind and gives it back
when the binding moves to another body.
Anything else takes the character over by writing those three fields from its
own `update()` — an AI brain, a networked peer, a replay, or gameplay code
that wants the character committed during an attack. The write works from
**any** `executionOrder`, because the refill happens after the read: whatever
is in the bus when the controller next reads it is what the character does.
On the local player's body the controller fills the bus from the map once
more just before the read, so a press moves the body on the frame it
arrives, and that fill takes only the fields nothing has written since the
last refill. A write counts whatever value it carries
(`ref:fieldWrites(name)`), so a writer that holds the body still by writing
no movement and the jump let go keeps it still through every press.
- A writer ahead of the controller (`executionOrder` below `-100`) is acted on
the same frame.
- A writer behind it is acted on the next frame.
- A writer that writes some of the fields leaves the others to the map: one
that steers with `inputX` / `inputZ` alone leaves the jump to the player's
jump control, which jumps on the frame it is pressed.
- Stop writing, and the character stops one frame later; on the local
player's body the map has it back instead.
- Pausing gameplay empties the bus, so a character frozen mid-stride stands
where it was paused and a writer that had it committed says so again.
`inputX` / `inputZ` are a world-space velocity in units per second, the walk
the character is asked for: the controller takes its walk toward them at its
`acceleration` and `braking` (see "Movement feel" below), so scale them
yourself rather than expecting `moveSpeed` to. `inputJump` asks for one jump
and the next update consumes it. `inputJumpHeld` says the jump control is
held: write it `true` on every frame the jump is held, and a jump asked for
with it is cut short when it stops (with `minJumpHeight` above 0), on the
step it takes off when it stopped while the request waited in the
`jumpBuffer`; a jump asked for without it rises its full height.
A component that walks the character due north, whatever the input map says:
```lua
-- Northbound.component/init.luau
declare { executionOrder = 50 } -- anywhere works; 50 runs after the controller
public = {
speed = Field.number(4.0, Sync),
}
function update(_dt: number)
local cc = public.entity.component.get("CharacterController")
if cc == nil then return end
cc.inputX = 0
cc.inputZ = -public.speed
end
```
`WASDInput` is the same pattern shipped as a component: it reads an input map
of its own and writes the bus of whatever component `targetComponent` names,
which is how a mover that reads no controls of its own gets driven. On a
CharacterController — which reads `move`, `sprint` and `jump` from its own
`inputMap` — a WASDInput writes the bus every frame at its own `speed`, and
that is the speed the character walks at. `CharacterController.install` adds
one when `input = true` asks for it.
## The control scheme
`inputMap` is the scheme the character answers to. It reads three controls from it, each on its own:
- `move` — an axis2, projected against the active viewport camera so "forward" is into the screen. The camera turns for the frame in its look phase, before the controller reads it, so a look that turns the camera turns the walk on the same frame.
- `sprint` — held, multiplies `moveSpeed` by `sprintMultiplier`.
- `jump` — pressed, asks for one jump.
A map declaring only some of the three drives the character with those: a scheme with no `sprint` holds one gait, a scheme with no `jump` stays on the ground. The character logs which controls the map left out and names the map, so a game with three verbs ships a three-control scheme. A field naming no map leaves the character answering nothing, and logs that too.
**Repointing it on a live character takes on the next frame.** The map the character was holding is stood down — its controls leave the live set and its touch buttons leave the screen — and the map named here is taken up in its place:
```luau
entity(bodyId).component.get("CharacterController").inputMap = asset.resolve("mygame.input.run", "inputMap")
```
Assigning the map the character already holds changes nothing, so re-stating the scheme leaves the live set where it is. While gameplay is paused the character holds no map at all (the editor's camera has the controls), and it takes whatever `inputMap` names when play resumes. A character that is not the local player's body holds no map either, and takes whatever `inputMap` names when it is bound as that body.
## Movement feel
How the character starts, stops, turns, jumps and falls is set by its feel
fields. The same settings drive the package's character module
(`CharacterController.attach` / `Velocity.resolve`), through one set of rules
(`movement.feel` of `characterController.module`).
On the ground:
- `acceleration` (m/s², default 20) is how fast the walk speeds up toward the
walk asked for. At 20 a 2.5 m/s walk is reached in 0.125 s and a 7 m/s
sprint in 0.35 s.
- `braking` (m/s², default 30) is how fast it slows: to a stop when nothing is
asked, down to a slower walk, and away from a heading the request turned
from. A turn sheds the old heading at `braking` while it builds the new one
at `acceleration`, and a reversal at speed brakes to a stop before it speeds
up the other way, rather than flipping in a frame.
- Either at 0 reaches the walk asked for on the frame it is asked, which is
how the `instant` preset keeps a character that answers with no ramp.
- The walk is the character's own, on top of what carries it: on a belt or a
moving deck it speeds up relative to the surface; on a slope it follows the
ground. `velocityX` / `velocityZ` read the ramp as it happens, so
`Locomotion` blends its gait from the speed the body really moves at, and a
networked peer sees the motion the owner simulated.
The jump:
- `jumpHeight` (m) and `jumpApexTime` (s) state a jump directly: with both, a
full jump rises exactly `jumpHeight` and tops out `jumpApexTime` after
take-off, at any frame rate. `jumpHeight` alone rises that high against the
character's gravity; `jumpApexTime` alone takes off at `jumpForce` and tops
out that long after. At 0 (the default) a jump takes off at `jumpForce` m/s
against the character's gravity.
- `minJumpHeight` (m) above 0 makes the jump control's release cut the jump
short. Let go at take-off, it rises `minJumpHeight`; let go during the rise,
it rises `minJumpHeight` above where it was when let go; held to the top, it
rises the full height. A real tap holds the control a few frames, and a fast
jump has risen some way by then: a `minJumpHeight` of 0.8 m on a jump taking
off at 8.3 m/s gives a 0.05 s tap a hop near 1.3 m. Set `minJumpHeight`
below the hop a tap should give; the presets set it so. On the local player's body the input
map's `jump` control holds it (keyboard, gamepad and touch alike); a writer
of the bus holds it with `inputJumpHeld`, and the module with
`CharacterController.jump(id)` until `CharacterController.releaseJump(id)`.
- `fallGravityMultiplier` (default 1) scales gravity while the character falls,
from the top of a jump or off a ledge: above 1 a jump rises floaty and comes
down fast, below 1 it drifts down.
- `maxFallSpeed` (m/s) above 0 caps the fall.
- One request is one jump. `inputJump = true` (or one press of `jump`) spends
one jump, and `jumpCount` counts it. A character with `maxJumps = 2` jumps
once on the request and keeps its second jump for the next request it gets
in the air. Landing gives every jump back.
- `coyoteTime` (s) is how long after walking off the ground the first jump is
still the jump from the ground. Past it that jump counts as spent, so with
`maxJumps = 2` a request in the air takes the air jump, as it does after a
jump from the ground.
- `jumpBuffer` (s) keeps a request made in the air with no jump left, which
jumps the moment the character lands; the jump it takes closes the buffer.
A tap made just before landing takes off as a tap: with `minJumpHeight` set
it gives the short hop.
- In the air the velocity across the ground carries on and turns toward the
walk the bus asks for at `airControlFactor * 10` of the way a second. A run
held through a jump keeps its speed, so a 5 m/s running jump of about a
second covers about 5 m; letting go of the stick slows the character the
same way, and a new heading takes over gradually. The higher the factor the
faster it answers: at 6 or more it takes the asked-for walk within one 60 Hz
frame, and at 0 it keeps the take-off velocity untouched.
Four presets set every feel field at once. Apply one to a character, or name
it in `CharacterController.install(id, { preset = "weighty" })`:
```luau
preset.apply("characterController.presets.weighty",
{ entity = id, component = "CharacterController" })
```
| Preset | Ground | Jump |
|--------|--------|------|
| `instant` | no ramp: starts, stops and turns the frame it is asked | `jumpForce` against gravity, full height however it is pressed, no fall scaling or cap |
| `responsive` | 40 m/s² up, 50 m/s² braking: quick and crisp | 1.3 m in 0.38 s, let go at take-off 0.25 m, falls at 1.6x, capped at 20 m/s |
| `weighty` | 6 m/s² up, 6 m/s² braking: a heavy body that commits to its heading | 0.8 m in 0.36 s, full height every press, falls at 2x, capped at 25 m/s, little air control |
| `floaty` | 25 m/s² up, 15 m/s² braking: light, slides a little into stops | 2.5 m in 0.6 s, let go at take-off 0.3 m, drifts down at 0.6x, capped at 6 m/s, strong air control |
Each field can be set on its own afterwards, on top of a preset:
```luau
local cc = entity(id).component.get("CharacterController")
cc.jumpHeight, cc.jumpApexTime = 1.5, 0.45 -- a full jump: 1.5 m, top at 0.45 s
cc.minJumpHeight = 0.4 -- let go at take-off: 0.4 m
cc.fallGravityMultiplier = 1.8 -- comes down faster than it went up
```
## Stairs and steps
A grounded character walks up a riser or curb no taller than `stepHeight`
and down a drop no deeper than it. The capsule lands on the next tread in
the frame it reaches it and keeps that exact height, so the walls, the
ground and every query see the character where it stands.
What the player sees climbs smoothly: the character's direct children that
hold no collider and no physics body, with none below them (the body mesh, a
name label) are drawn
shifted back by the riser and close on the capsule as a critically damped
spring of `stepSmoothing` seconds (default `0.1`: about three fifths of a
step in that time, nine tenths in twice it). A rise or drop the ground's
slope accounts for, on a ramp or a hill, is drawn as it happens; a
character placed by something else (a teleport, a respawn) is drawn where it
was placed. `stepSmoothing = 0` draws the body on the capsule every frame.
The character's module (`characterController.update`) smooths its steps by
the same rule, through `movement.stepSmoothing`.
## Platforms, belts and the contact filter
The character meets the surfaces content declares on colliders the way a
rigid body does. Its ground, wall and ceiling queries are cast for the
character's own entity as their mover (`Physics.raycast(..., { mover = id })`
and the same option on the shape casts), so the contact rules the physics
step applies to bodies apply to it too:
- **One-way platforms.** A collider whose `oneWay` points up holds the
character from above only: it jumps up through the platform from below and
lands on top of it, and walks through its sides.
- **Dropping through.** `Physics.passThrough(character)` drops it through the
one-way colliders it stands on (or, with a second argument, only those that
entity owns). It falls through under its own gravity and meets each again
once it is clear of it.
```luau
Physics.passThrough(player) -- drop through what it stands on
Physics.passThrough(player, platform) -- drop through this platform alone
```
- **Moving surfaces.** Standing on a collider whose `surfaceVelocity` moves (a
conveyor belt, a treadmill, an escalator) carries the character at that
velocity on top of its own walk. It keeps the carry as momentum when it
jumps or walks off, and air control (`airControlFactor`) takes it back
toward the walk it asks for.
- **Moving bodies.** Standing on a body that itself moves or turns (a lift, a
moving platform, a turntable, a raft, a ship's deck, a train car) carries
the character with it: each frame the point under its feet goes where the
body took it, and the character turns with the body's turn about up, with
its own walk on top. It rises and descends with a lift without leaving the
ground, and keeps the body's motion at its feet as momentum when it jumps or
walks off. In the air it goes on moving with that motion until it lands, the
way a crate thrown off the deck does: air control (`airControlFactor`) steers
its walk relative to it, so a jump in place on a moving deck comes down on
the spot it left, and a wall it meets in the air stops the part of it the wall
is in the way of. A kinematic body a script moves (`localPosition` writes,
`Physics.setVelocity`), a dynamic body the simulation moves and a transform
something animates all carry it alike. The body is read where the frame
draws it (`Physics.drawnPose`), and the character is seated on the ground as
drawn, so the two stay in step on screen at any frame rate and physics tick
rate. A body a script moves after this component's `update` (an
`executionOrder` above -100, or a task) carries the character on the next
frame. The momentum a kinematic body or an animated transform leaves the
character with is how fast it carried the feet over the last tenth of a
second (and at least the last six frames), however the frames fell against
the physics ticks, and a body that vanishes from under the character
leaves it the same. A character something else moves (a teleport, a
respawn, a script writing its position) rides nothing until it stands on
a body again. A move faster than 150 m/s over the frame
(`StatedWalk.TELEPORT_SPEED`), or longer than 2.5 m over a frame of any
length (`StatedWalk.PLACEMENT_DISTANCE`), places it: it stands where it was
put at rest, with none of the fall, jump, walk or carry it had where it was
taken from, and with no footing on the ground it left: until it stands
again it has no `coyoteTime` to jump from, so with `maxJumps = 1` a
character put in mid-air takes no jump there. A shorter, slower move
carries it (a room-scale step in XR, a script pushing it along), and its
fall and walk go on; writing back the position it
already stands at moves it nowhere. In a multiplayer session the
character states its pose relative to the kinematic or dynamic body it
rides, and through a jump off it until it lands (`multiplayer.setPoseFrame`,
read back with `multiplayer.poseFrame`): every other peer draws it on that
body where that peer draws the body, so a rider on another peer's moving
deck holds its spot there on every screen.
```luau
local lift = entity.spawn("lift")
lift.component.add("BoxCollider", { half = { 1.5, 0.1, 1.5 } })
lift.component.add("Physics", { kind = "kinematic" })
Physics.setVelocity(lift.id, 0, 1, 0) -- the character on it rides up
Physics.setAngularVelocity(lift.id, 0, 1, 0) -- and turns with it
```
- **The contact filter.** Give the character a collider with a `contactTag`
(a trigger capsule is enough) and `Physics.setContactFilter` answers its
pairs: a collider whose tag the filter answers `"ignore"` or `"sensor"`
with the character's tag is one the character walks through.
```luau
player.component.add("CapsuleCollider", { isTrigger = true, contactTag = "player" })
Physics.setContactFilter("player", "ghostWall", "ignore")
```
## Launching, knockback and momentum
Give the character speed it did not choose (a launch pad, a spring, a
knockback from a hit, a rope let go of, a respawn that sends it off) with
`setVelocity` or `addVelocity` on its controller, in m/s in world space. The
same verbs on `Physics` reach it too, so `Physics.setVelocity(player, ...)`,
`Physics.addVelocity(player, ...)` and `Physics.getVelocity(player)` work on a
character as on a rigid body. A character holds no mass, so an impulse is
given as the change of speed it makes (`addVelocity`), and
`Physics.applyImpulse` moves it nowhere and says so in the log.
```luau
local cc = entity(player).component.get("CharacterController")
cc:addVelocity(0, 14, 0) -- a jump pad: straight up, 10 m high at 9.81 m/s²
cc:setVelocity(6, 10, 0) -- a launch pad: thrown up and along +X
cc:addVelocity(away.x * 8, 4, away.z * 8) -- knockback away from a hit
Physics.addVelocity(player, 0, 14, 0) -- the same through Physics
local v = cc:getVelocity() -- { x, y, z }, world space
```
`setVelocity` replaces the velocity the character has; `addVelocity` adds to
it (to its walk, its fall and any motion kept from a body it left). Called
several times before the character's next frame, `setVelocity` calls replace
one another and `addVelocity` calls add up, on top of the last `setVelocity`.
Either takes effect on the character's next frame, after anything that
placed it this frame, so a respawn onto a launch pad launches. Each takes
`(x, y, z)`, a `vector` or a table `{ x, y, z }`, and answers `true`.
The controller carries the velocity on through its own movement, the way it
carries a jump or the motion of a platform it leaves:
- **Standing, with no speed up**, the part across the ground is the
character's walk: `braking` slows it to a stop (or to the walk its input asks
for), so 6 m/s with a `braking` of 5 slides 3.6 m. Walls stop it a skin short
of their face and slide it along them, and a dynamic body in the way is
pushed as a walk pushes it.
- **With any speed up**, it leaves the ground on that frame and reads
`grounded` false until it lands. No jump is spent, and the jump it could
have taken from the ground in `coyoteTime` is gone, so a character with
`maxJumps = 2` has its air jump and one with 1 has none. It rises and falls
under its gravity (a launch rises its full height whether the jump control
is held or let go), a ceiling stops the rise, and on a moving body it adds
the body's motion as it leaves, as a jump does.
- **In the air**, the speed across the ground it was given flies on: air
control (`airControlFactor`) steers only the walk the input asks for, on top
of it, as it does over the motion kept from a platform. A wall met in the air
stops the part of it the wall is in the way of.
- **Landing**, what is left of it becomes the walk, and `braking` slows it on
the ground.
The movement is integrated exactly for each part of a frame, so a launch rises
the same height and lands the same distance away at 30 and at 120 frames a
second, within the step of the frame it lands on. On a body the character
stands on, the velocity is relative to that body. In a multiplayer session the
peer that moves the character applies it (the owner of a player's body, or
the peer it is bound to) and every other peer sees the motion through the
character's replication. On another peer's replica both calls leave the velocity
as it is and answer `false` (`Physics.setVelocity` and `Physics.addVelocity`
say so once in the log), so a hit landed on another player's body is sent to
the peer that moves it (a `Sync` event or `multiplayer.send`) and given there.
## Other characters
Characters meet one another as solid bodies. Every entity carrying a
`CharacterController` is an upright capsule of its `radius` and `height` to
every other character's wall pass (`physics.characters`), so two characters
walking into each other stop a skin apart, a character meeting another off
centre slides around it, and `blocked` reads true while a walk presses into
another character. The same holds for the local player, an NPC and another
player's body.
A character is a body while its entity is active and its controller enabled:
one set inactive (`entity(id):setActive(false)`) or with its controller
disabled (`enabled = false`) lets the others walk through it until it is
switched back on.
The push rule:
- A walk never moves another character. Each peer moves only the characters
it owns, against where it sees the others, so two players' bodies meet on
both peers' screens.
- Two characters that overlap (placed into one another, two spawned at one
point, a body the network shows a frame late) move apart at up to 2 m/s
each, each taking half of the overlap, and never through a wall. A pair
pressed together stands still a skin apart.
- A character gives way to no body moving into it: the one walking in is the
one stopped, on the peer that moves it, so a player walking into a standing
one never drives it along, however late each peer sees the other.
- Only bodies sharing some height meet: a character jumping over another
passes above it, and one coming down onto another's head is moved off it to
the side.
Which characters pass through which is the contact filter's to say, by each
character's `contactTag` (`"character"` unless content names another):
```luau
Physics.setContactFilter("character", "character", "ignore") -- nobody blocks anybody
ghost.component.get("CharacterController").contactTag = "ghost"
Physics.setContactFilter("ghost", "character", "ignore") -- the ghost walks through people
Physics.setContactFilter("redTeam", "redTeam", "ignore") -- teammates pass, foes block
```
## Triggers, pickups and the bodies it walks into
The character holds no rigid body: it states its capsule (`Physics.setWaterVolume`),
`height` tall and `radius` round, standing on its feet. That capsule is how
the rest of the world meets it:
- **Triggers and pickups.** A trigger collider hears the character enter and
leave it as it hears a body (`Physics.onTrigger(zone, fn)`, with `other`
the character's entity), and a listener on the character
(`Physics.onTrigger(character, fn)`) hears every trigger it goes through.
Every engine the character exists in hears it, the remote players' bodies
included, so a zone counted on each peer counts every player. A trigger on
an entity beneath the character (a sensor it carries) rides with it and
does not hear it.
- **Water.** `Physics.onWater` hears it go in and out of the water and
`Physics.immersion` reads how deep it stands.
- **Pushing.** A dynamic body the walk runs into is pushed along the walk:
the walk stops at it as at a wall, and the body is given the impulse that
brings its speed along the walk up to the walk's, with at most `pushForce`
newtons (400 by default) behind it. On level ground a body moves once
`pushForce` passes its friction coefficient times its weight, so at the
default a 5 kg crate goes along at the walk with the character behind it and
a 500 kg one stands like a wall. `pushForce = 0` makes every body a wall.
- **Bodies moving into it.** A body that moves into the character puts it
back outside, as a wall that moved into it does.
```luau
local player = layers.active.players.localPlayer.avatar
Physics.onTrigger(coin, function(e)
if e.kind == "enter" and e.other == player.id then collect(coin) end
end)
player.component.get("CharacterController").pushForce = 150 -- a weaker shove
```
## Telemetry
These read back what the mover did on the frame just simulated:
- `grounded` — standing on ground no steeper than `maxSlopeAngle`.
- `falling` — in the air and descending.
- `sliding` — on ground too steep to stand on, being carried down it.
- `blocked` — the character asked to move horizontally and the wall pass left
it with none of that movement: pressed into a wall, or wedged where two
surfaces meet. This is what tells a character standing still apart from one
whose walk is being refused.
- `slopeAngle` — the angle, in degrees, of the ground under it.
- `velocityX` / `velocityY` / `velocityZ` / `horizontalSpeed` — its velocity,
across the frame it stands in (`frame`). `getVelocity()` reads it in world
space, with any velocity given since its last frame.
- `jumpCount`: jumps used since it last landed. Walking off a ledge counts
the jump from the ground as used once `coyoteTime` has passed.
## Standing still
A character standing on the ground with nothing asking it to move rests: it
takes no movement step and writes none of its fields, so a crowd of idle
characters costs little more than the check each one makes that nothing has
reached it. It takes its step again on the frame anything does: a write to its
input bus or any of its fields, its feet moved by something else, the ground
or the body it rides moving or changing (taken away, switched off, passed
through, its surface set moving), a collider coming to overlap it, another
character moving within reach, the gravity at its feet changing, or its being
bound as the local player's body. Entities spawned and despawned elsewhere in
the world leave it resting. Telemetry reads what it read on the frame it came
to rest.
`stats()` reads how its frames went:
```luau
local s = entity(id).component.get("CharacterController"):stats()
print(s.resting, s.stepFrames, s.restFrames)
```