# data
[[describe]] Say what the module provides and who calls it.
# movement
[[describe]] Say what the module provides and who calls it.
# physics
[[describe]] Say what the module provides and who calls it.
# state
[[describe]] Say what the module provides and who calls it.
# defaults
> 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.
Default configuration presets for the character controller. Each
preset is a flat `Config` table that `CharacterController.attach` /
`install` merges over with user overrides. No behaviour, no state —
just constants.
## Exports
- `M.standard: Config` — baseline humanoid tuning. Used when no user
config is supplied to `attach`.
- `M.platformer: Config` — higher gravity, stronger jump, double jump,
generous coyote time, high air control.
- `M.heavy: Config` — taller capsule, lower max slope, weaker jump,
minimal air control.
Types:
- `Config = { height, radius, maxSlopeAngle, stepHeight, gravity, jumpForce, coyoteTime, jumpBuffer, maxJumps, airControlFactor, groundSnapDistance, stepSmoothing, skinWidth }`
## Usage
```luau
local Defaults = require("characterController.characterController.data.defaults")
-- Use a preset directly:
CharacterController.attach(entityId, Defaults.platformer)
-- Or merge selective overrides:
local cfg = {}
for k, v in pairs(Defaults.standard) do cfg[k] = v end
cfg.jumpForce = 8.0
CharacterController.attach(entityId, cfg)
```
## Notes
- Pure data, no engine calls. Safe to require at module load time.
- These tables are shared singletons — mutating `Defaults.standard`
in place will affect every later `attach` that uses it. Copy
before mutating.
# Locomotion
Blend-space-driven locomotion for entities running the
characterController package. Feeds a single 2D blend space (strafe-angle
on X, speed on Y) with idle / walk-{F,L,R,B} / run-{F,L,R,B} / sprintF
clips from the character's own walk.
The walk is what the character's `CharacterController` states each frame it
moves it: its walk across what it stands on, so a body carried by a conveyor,
a moving deck or a lift while it stands still plays its idle, and the walk it
is asked for. The body turns toward the walk it is asked for at whatever speed
it asks (a light stick push, a walk into a wall the walls refuse), and with
none asked toward its velocity once that is faster than `moveDeadzone`. A
body that carries neither a `MovementState` nor a `CharacterController` reads
the walk the nearest of its ancestors with a `CharacterController` states, so
a body parented under a root a controller walks idles on a conveyor and turns
toward a wall it is asked to walk into, as that root does. On a frame nothing
states the walk (another peer's avatar the sync moves, a body a script moves)
the velocity is measured: from the entity's `MovementState`, or its
`CharacterController` without one, against its parent; and on a body that
carries neither, from its position in the world, so a body parented under the
root an NPC's brain and navigation move walks and faces with that root.
The strafe angle is the signed angle from the body's facing to
its velocity, positive toward the body's right (`forward x up`): the R
clips sit at +90, the L clips at -90 and the B clips at 180. Each
clip's point sits at the speed the clip carries this body at: its
retarget bake measures how fast the ground passes under the
stance foot on this body's legs, so the feet move with the ground at
whatever speed the body moves. A clip that plays without a measured
speed sits at its gait's `walkSpeed` / `runSpeed` / `sprintSpeed`.
Pair on the same entity (or a parent of) a `SkinnedModel`. The
component creates the AnimGraph, polls for the SkinnedModel child
once start() has run, registers the clips as blend-space points and
plays the graph. `update()` damps speed + angle and writes them to
the active blend space each frame.
Once every clip has bound, the component hands the graph to the engine
(`AnimGraph:runNatively`): the engine reads the walk the mover states, or
measures the root's velocity from its position, turns the body as above, damps the speed and angle and evaluates
the blend space every frame, and the component's `update` is held. A body
the sync moves (another peer's avatar), an NPC and the local player's own
body all walk with no script running for their pose. The component takes
the graph back when one of its fields changes or another component changes
the graph (a layer spliced over it), and runs it in script while the graph
holds a node the engine does not run, a clip that drives blend shapes, or
its velocity is read from a `CharacterController` without a `MovementState`.
`component.get("Locomotion"):stats()` reads
`{ native, handle?, frames?, refusal?, motion, space }`: where the graph runs,
why not in the engine when it does not, whether the velocity is the walk the
mover stated (`motion = "stated"`) or a measured one (`"measured"`), and
whether a measured velocity is the body's motion against its parent
(`space = "local"`) or in the world (`"world"`).
## Facing in multiplayer
The body's facing is the rotation of its anchor, the child of the root that
holds the skinned body, and only the peer that owns the body turns it. The
component names that child with `multiplayer.syncChildPose`, so its local
pose travels with the synced root: every other peer draws the facing the
owner states, a short delay behind on the timeline the root is drawn on, at
join, after the body stops and through a turn in place alike (a script that
turns the anchor on the owner's peer is drawn turned everywhere). On a peer
that draws it so, `multiplayer.childPoseFromOwner(anchor)` reads true and the
component, in script or in the engine, reads its strafe angle from that
facing and leaves the anchor's rotation as the owner states it.
## Jumping, falling and landing
`jumpAnim`, `fallAnim` and `landAnim` are the air poses: the take-off and
rise, the fall, and the landing. With any of them set (the `synty` preset sets
all three, and the built-in humanoid avatar uses it) the blend space and those
clips sit under one Mixer, and the body moves between four states by the
motion of its root:
- **ground**: the locomotion blend plays.
- **rise**: the body is off the ground and moving up faster than 1 m/s. The
take-off clip plays from its start.
- **fall**: the body is off the ground and moving down faster than 1 m/s (a
walk off a ledge), or its rise has stopped. The fall clip loops.
- **land**: the ground is under the body again. The landing clip plays from its
start and fades into the locomotion blend over `landTime` seconds.
The body is off the ground while nothing stands within 5 cm below its feet
across its footprint. The footprint is the disc its `CharacterController`
stands on, its `radius` less its `skinWidth` (0.25 m without one), and the
5 cm are counted from the ground the feet stand a `skinWidth` above, so a body
standing on the edge of a ledge, or with a wide skin, reads the ground its
controller stands on. A sphere of the footprint's radius is swept down past
the colliders the character carries, far enough to reach an edge at the rim
of the footprint, and the surface it meets counts where the sphere touched it.
A change of the controller's `radius` or `skinWidth` reaches the sweep on the
next frame (the controller calls `footingChanged()`). A body on nothing that
moves neither up nor down (a preview, a mannequin) keeps the locomotion blend.
Each pose's weight moves toward its state's at
`1 / airBlendTime` a second. A slot left nil, or whose clip failed to bind, is
stood in for: the take-off by the fall, the fall by the take-off, and the
landing by the locomotion blend. A clip that failed to bind keeps the graph in
script, and `stats().refusal` names the clip.
The engine runs the air states with the rest of the graph, so the local
player, an NPC and another player's body the sync moves all jump, fall and
land the same way with no script running for their pose.
```luau
local loco = entity(id).component.get("Locomotion")
loco.jumpAnim = asset.resolve("A_Jump_Running_Masc", "animation")
loco.landTime = 0.2
```
# machine
> 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.
State machine helper for the builtin character controller. Owns the
state table shape (grounded / falling / sliding / wall contact /
blocked / jump counts / moving-platform tracking) and the timing rules
(coyote time, jump buffering, multi-jump cap) that the controller
consumes each tick.
Pure logic — no engine globals beyond `entity()` for platform position
lookups.
## Exports
- `M.new() -> State` — allocate a fresh state with default values.
- `M.update(state: State, groundHit, wallHit, ceilHit, vel, config, dt, now)` — run ground/wall sensors and update grounding, timing, and moving-platform fields.
- `M.shouldJump(state: State, config: Config, now: number) -> boolean` — decide whether a queued jump should fire this tick.
- `M.executeJump(state: State, config: Config) -> number` — mutate state for a jump and return the Y velocity to apply.
- `M.requestJump(state: State, now: number)` — register a jump press (may be deferred via jump buffer).
- `M.clearJumpRequest(state: State)` — drop any pending jump request.
Types:
- `Vec3 = { x: number, y: number, z: number }`
- `RaycastHit = { point?, normal: Vec3, entityId?, _sliding?, _blocked? }` — shape of `Physics.raycast`-style hits the controller produces.
- `State = { grounded, falling, sliding, wallContact, blocked, wallNormal, velocity, groundNormal, slopeAngle, jumpCount, timeSinceGrounded, timeSinceWallContact, onMovingPlatform, platformEntity, ...internal timing fields }`
- `Config = { maxJumps?, coyoteTime?, jumpBuffer?, jumpForce? }` — character tuning fields read each tick.
## Usage
```luau
local State = require("characterController.characterController.state.machine")
local s = State.new()
State.update(s, groundHit, wallHit, ceilHit, vel, config, dt, now)
if State.shouldJump(s, config, now) then
local jumpY = State.executeJump(s, config)
end
```
## Notes
- `update` is destructive — it mutates `state` in place. The state table
is the single source of truth; callers should not rebuild it each
tick.
- The jump-buffer window persists across frames; `shouldJump` consumes
it via the `_jumpBufferTime`/`_jumpRequested` pair.
- `platformEntity` is the entity the character stands on while grounded.
The controller module carries the character with that body's motion
(`physics.platform`) and sets `onMovingPlatform` on a frame the body moved
it.
- `blocked` is true on a frame the wall pass left the character with
none of the horizontal movement it asked for — `wallHit._blocked`,
which `Velocity.resolve` marks. It is what tells a character standing
still apart from one whose walk is being refused.
- `ceilHit` is accepted for API symmetry but currently unused; future
ceiling-bump handling will read it without changing the signature.
# stepSmoothing
> 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's drawn body climbs a step its capsule takes at once. A
grounded character walking up or down a stair is put on the next tread in the
frame it reaches it: its capsule, and so its entity, rises or drops a whole
riser in one frame, and keeps that exact height. The character's direct
children that hold no collider and no physics body, with none below them
(its body mesh, a name label) are drawn shifted along its up by an offset that takes the riser back
and closes to zero as a critically damped spring, so the body is seen to climb
smoothly while the walls, the ground and every query see the character where
it stands.
A rise or drop the ground's slope accounts for (a ramp, a hill) is the walk
itself and is drawn as the capsule moves; only what goes past it (a riser, a
curb, a step down) is smoothed. The offset is held within the character's
step height, and a character placed by something else (a teleport, a respawn)
is drawn where it was placed at once.
The `CharacterController` component and the character module's `update` both
climb through here, so every character smooths its steps by one rule. The
component's `stepSmoothing` field and the module config's `stepSmoothing` are
the spring's smoothing time in seconds (default `0.1`); `0` draws the body on
the capsule every frame.
## Exports
- `StepSmoothing.new() -> Smoothing`: a fresh record for one character, no
offset and no child shifted, owned by the controller that moves it.
- `StepSmoothing.climbed(state, rise, travel, slopeAngle, stepHeight) -> offset`:
takes in one grounded step's rise along up. The part of `rise` past what a
slope of `slopeAngle` degrees gives `travel` metres across the ground puts
the drawn body back by that much, held within `stepHeight`.
- `StepSmoothing.settle(state, entityId, smoothTime, dt) -> offset`: closes the
offset by `dt` seconds of the spring and draws the entity's drawn children
at it. Costs nothing on a frame with no offset and no child shifted. The
record keeps its read of the entity's children and updates each child's
record in place, so a frame it closes allocates nothing while the scene's
structure stands; the first frame it closes after the structure changes (an
entity anywhere spawned, despawned, reparented, renamed or turned on or
off) reads the children again.
- `StepSmoothing.clear(state, entityId)`: draws the children back on the
capsule at once, for a character placed by something else, no longer moved
by its controller, or going away.
- `StepSmoothing.offset(state) -> number`: the offset along up in metres,
negative while the body is drawn below the capsule (after a step up).
- `StepSmoothing.active(state) -> boolean`: whether the body is drawn off the
capsule now; a controller keeps stepping a character while it is.
## Usage
```luau
local StepSmoothing = require("characterController.characterController.movement.stepSmoothing")
local smoothing = StepSmoothing.new()
-- In each grounded step that ended on the ground:
StepSmoothing.climbed(smoothing, dy, math.sqrt(dx * dx + dz * dz), slopeAngle, stepHeight)
-- Once a frame, after the steps:
StepSmoothing.settle(smoothing, entityId, 0.1, dt)
```
# 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)
```
# 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)
```
# feel
> 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 rules that give a character its feel, shared by the `CharacterController`
component and the package's character module (`Velocity.resolve` and the
state machine), so both answer the same settings the same way.
## Exports
- `Feel.DEFAULTS`: the feel a character has when nothing states another
(`acceleration` 20, `braking` 30, `jumpForce` 5, `jumpHeight` 0,
`jumpApexTime` 0, `minJumpHeight` 0, `fallGravityMultiplier` 1,
`maxFallSpeed` 0).
- `Feel.walk(vx, vz, wantX, wantZ, acceleration, braking, dt) -> (vx, vz, dx, dz)`:
the ground velocity after `dt` seconds of walking toward the request, and
the distance covered across the ground over them, exact for that motion. It
speeds up along the request at `acceleration`, slows at `braking`, sheds
the part across the request at `braking`, and brakes to a stop before a
reversal speeds up the other way. 0 for either reaches the request at once.
- `Feel.launch(settings, pull, held) -> (speed, rise)`: the take-off speed of
a jump and how it rises, from `jumpForce`, `jumpHeight`, `jumpApexTime` and
`minJumpHeight`, against the gravity `pull` (m/s², positive pulling down).
`held` says the jump was asked for with the jump control held, which makes
it one a release cuts.
- `Feel.release(vy, rise, held) -> (vy, rise)`: a jump asked for held, once
the control reads let go during its rise (on the step it takes off, for a
request let go before then), is cut to the speed that tops it out
`minJumpHeight` above where it was.
- `Feel.vertical(vy, dt, rise, pull, settings) -> (dy, vy, rise)`: one step
along up off the ground, integrated exactly: a rising jump against its own
gravity, a fall at `pull * fallGravityMultiplier`, no faster than
`maxFallSpeed`. A step crossing the top switches gravity there, so the stated
height and apex time hold at any frame rate.
- `Feel.jumpsAfter(jumpCount, maxJumps, footing) -> number?`: the jump count a
granted request leaves, or nil. On its feet or within coyote time
(`footing`) a character takes its first jump; past it the jump from the
ground counts as spent and a request takes the next jump `maxJumps` leaves.
## Usage
```luau
local Feel = require("characterController.characterController.movement.feel")
local dx, dz
vx, vz, dx, dz = Feel.walk(vx, vz, wantX, wantZ, 20, 30, dt)
local vy, rise = Feel.launch({ jumpHeight = 1.2, jumpApexTime = 0.4, minJumpHeight = 0.4 }, 9.81, true)
vy, rise = Feel.release(vy, rise, jumpHeld)
local dy
dy, vy, rise = Feel.vertical(vy, dt, rise, 9.81, { fallGravityMultiplier = 1.5, maxFallSpeed = 20 })
```
# velocity
> 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.
Velocity integration and per-frame movement resolution for the
character controller. Owns no state — every call takes the current
position / velocity / config / state and returns the new position
delta plus the updated velocity. Internally uses the `Ground`,
`Walls`, and `Ceiling` raycasting helpers.
## Exports
- `M.resolve(pos: Vec3, vel: Vec3, moveInput: MoveInput, config: Config, state, dt: number, selfId: string) -> (dx, dy, dz, vx, vy, vz, groundHit, wallHit, ceilHit)` —
apply gravity + air control, resolve wall slide / corner pin / the
steps a grounded body climbs (`Walls.move` with `stepHeight`) /
ceiling bonk / ground snap on the ground the footprint stands on
(`Ground.support`) / slope projection / steep-slope slide, in that
order.
Types:
- `Vec3 = { x: number, y: number, z: number }`
- `MoveInput = { x: number, z: number }` — world-space horizontal input.
- `Config = { height?, radius?, maxSlopeAngle?, stepHeight?, gravity?, airControlFactor?, groundSnapDistance?, skinWidth?, acceleration?, braking?, fallGravityMultiplier?, maxFallSpeed? }`
## Usage
```luau
local Velocity = require("characterController.characterController.movement.velocity")
local dx, dy, dz, vx, vy, vz, groundHit, wallHit, ceilHit =
Velocity.resolve(pos, vel, moveInput, config, state, dt, selfId)
```
## Notes
- The function is pure: it returns nine values but mutates nothing.
The caller is responsible for writing the position delta back via
`entity.localPosition.set` and updating its velocity field.
- Air control blends horizontal velocity toward the walk the input asks
for, at its full speed, with `airLerp = min(1, airControlFactor * 10 * dt)`:
a run held through a jump keeps its speed, and a turn or a change of speed
takes effect over `1 / (airControlFactor * 10)` seconds or so (at a factor
of 6 or more, within one 60 Hz frame). The blend is relative to
`state.keptMotion` (the motion kept from a moving body the character left)
when the state carries one, so the body goes on moving with it
(`Platform.steer`). Grounded mode uses direct assignment for responsive
feel.
- Ground cast distance is the larger of `groundSnapDistance` and
`stepHeight` plus two `skinWidth`s when grounded (the feet stand a skin
above the ground, and a second skin holds a riser of exactly
`stepHeight` in reach), so a body walks down stairs on its feet, and
`100` when airborne (so a fast fall doesn't tunnel past the floor).
Snap commit threshold is tight (the frame's own vertical travel),
so airborne ground hits don't snap unless they are within that
travel window.
- A grounded frame looks for ground above the feet as well, by the
rise its own travel covers on ground of `maxSlopeAngle` — that is
the ground a walking character climbs into. The seat takes it up to
the rise the surface it found covers over that travel, plus a step;
a surface further up stands across the path, and the character keeps
the ground it already has.
- Steep-slope (above `maxSlopeAngle`) hits set `groundHit._sliding =
true` so the state machine treats the frame as `sliding` rather
than `grounded`.
- A frame whose horizontal movement the wall pass cancels outright —
pressed straight into a wall, or wedged where two surfaces meet —
sets `wallHit._blocked = true`, so a refused walk reads as refused
instead of as a walk that happened to cover no ground.
- Step climbing only fires when `state.grounded`: the wall pass lifts the
body over a riser no taller than `stepHeight` that cut its walk short.
- On the ground the walk moves toward the input at `acceleration` and
`braking` (`Feel.walk` of `movement.feel`); along up the step is
`Feel.vertical`, which rises a jump `state._rise` holds against its own
gravity and scales and caps the fall. Missing settings read as
`Feel.DEFAULTS`.
# orbital_follow
> 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.
Three-ring orbit camera. Framing is authored as three rings around the follow target: a bottom, a centre and a top, each with a `height` above the target's origin and a `radius` out from its axis. Vertical look slides the camera along a smooth path through those rings, as far as it takes to turn the view by the look's angle; horizontal look orbits around them. The shape of the orbit is geometry you can see and edit rather than a pair of pitch limits you cannot.
Public fields: `follow`, `ringBottom` / `ringCenter` / `ringTop` (each `{ height, radius }`), `verticalAxis` (0 at the bottom ring, 1 at the top), `horizontalAxis` (the world heading the camera looks along, in radians about +Y from world +Z), `radiusScale`, `aimHeight` (the aim point above the target's origin), `damping` (per-axis time constants in seconds of the camera's offset from the point it frames: they soften a change of framing, a stick or touch look, a zoom or a recentre; a mouse look turns the camera on the frame the mouse moves), `horizontalLag`, `verticalLag`, `maxHorizontalLag`, `maxVerticalLag`, `jumpBand`, `leadTime`, `maxLead`, `leadSmoothing`, `recenterDelay`, `recenterTime`, `recenterTo`, `pullOutTime` (see below), `cameraRadius` (radius of the pull-in sweep; `0` turns the pull-in off), `cameraIgnore` (entities whose colliders the pull-in passes through), `occluderFade`, `occluderFadeWidth`, `bodyFade`, `bodyFadeDistance`, `fadeTime`, `fadeIgnore` (fading thin occluders and the subject's body, see below), `sensitivity` (radians the view turns per unit of look, the same in heading and in pitch wherever the rings run within about 78 degrees of round the aim point, as the default rings do at every `radiusScale` from 0.2 to 3; where they head more steeply toward or away from it, a vertical look moves the camera along them by five times that angle times its distance from the aim point), `invertY` (off by default: pushing the mouse forward looks UP, drawing the camera toward the bottom ring; on pitches the other way), `zoomSpeed`, `minRadiusScale`, `maxRadiusScale`.
The rig owns that heading. Binding a follow target aims it along the subject's facing, so the shot opens from behind whoever the camera is told to follow, and look input turns it from there and the recentre turns it back behind the subject once the player stops looking around (below). A facing that becomes known or is declared anew after the bind aims it behind the subject again, once for each change: a `Locomotion` or `LocomotionFull` arriving on the subject or leaving it, a body standing up under it, as an avatar that composes after the camera bound does, or the component's `forward` or `faceSign` changing (`CameraRig.facingSource` names what the facing is read from). The heading holds while the body turns. That is what makes the camera steerable for a character who turns to face where it is walking: hold "forward" and the character walks the line the camera looks down, instead of chasing a heading that moves as it turns.
The default rings frame a roughly 1.8 m humanoid standing at its origin: the centre ring sits above head height at the widest radius for a resting shot from behind and slightly above, the bottom ring drops to knee height and pulls in to look up, and the top ring climbs and tightens for a near-overhead look down.
In edit mode, or while play is paused, writing any framing field re-poses the rig immediately with damping bypassed, so editing a ring moves the camera to the shot that ring describes. While play runs, a write steers the rig: its next tick takes the new framing through the damping and the pull-in, the way it takes look input, so a script that turns the camera by writing `horizontalAxis` swings it round over frames, coming in ahead of a wall as a look does.
`follow` falls back to the `Camera.follow` slot when it is empty, so a rig selected through `Camera.behavior` tracks whatever that camera already follows.
Controls: mouse to orbit and to slide along the rings (play mode requests pointer lock, so no button is held), scroll to scale the ring radii.
```luau
local cam = entity(id).component.get("Camera")
cam.behavior = asset.ref("cameraRigs.orbital_follow", "component")
entity(id).component.get("cameraRigs.orbital_follow").ringCenter = { height = 2.6, radius = 6 }
```
## Following the subject: lag, lead and recentre
The camera frames a point that follows its subject's motion with lag, so a step, a stair, a landing, a start, a stop or a reversal is eased rather than copied:
- `horizontalLag` / `verticalLag` (defaults `0.2` / `0.25` s) are the time constants of that point closing on the subject across the ground and along up; `0` carries that motion on the frame it happens.
- `maxHorizontalLag` / `maxVerticalLag` (defaults `1.0` / `0.75` m) bound how far the subject gets from that point, however fast it goes, so the subject never leaves the middle of the frame by more.
- `jumpBand` (default `1.5` m) holds the camera's height through a jump: while the subject is off the ground (its `CharacterController`, or `MovementState`, reads it so) it rises up to this far above the framed height with the camera standing still, so a jump that lands where it took off moves the view along up not at all. Past the band the camera rises with the subject, which stands no farther above the framed height than the band, so a higher jump or a launch keeps it in the picture. A landing higher or lower is eased to over `verticalLag`, and a fall below the framed height is followed as on the ground. `0` follows every jump.
- `leadTime` (default `0.3` s), `maxLead` (`1.5` m) and `leadSmoothing` (`0.5` s): the aim runs ahead of the subject along its motion across the ground by its speed times `leadTime`, held to `maxLead` and eased as the subject starts, stops and turns, so the player sees where the subject is going. `0` aims at the subject.
- `recenterDelay` (default `2` s) and `recenterTime` (`1.25` s): in play, once look input has stopped for `recenterDelay` the heading turns back behind the subject over a time constant of `recenterTime`. `recenterTo` names what it turns behind: `facing` (the default), the way the subject visibly faces (its -Z, or the facing its `Locomotion` or `LocomotionFull` turns, `CameraRig.visibleForward`), or `motion`, the way it moves across the ground. While the subject moves the turn runs at the square of the share of its facing that points away from the camera (half the rate at 45 degrees off the view), so a subject running across the view or toward the camera keeps the heading where it is, rather than the camera and the subject turning each other round, and once it stops the turn waits `recenterDelay` again. A look the player makes while the subject stands holds the heading for as long as it stands: the wait starts once the subject moves off, and a subject that stops again with no look since turns behind after `recenterDelay`. A negative `recenterDelay` turns only on `rig:recenter()`, which turns the heading back now from any delay and ends a look's hold.
- `pullOutTime` (default `0.4` s): once the way is clear the camera eases back out over this time constant. The pull-in itself never cuts (below).
Setting the two lags and `leadTime` to `0` gives the camera that carries its subject's motion on the frame it happens. `rig:tracking()` answers how the camera follows right now: `lag` (how far the subject stands from the framed point), `lead`, `velocity` (the subject's, as the rig measures it), `recentering`, `idle` (seconds since look input) and `lookHeld` (a look the player made holds the heading while the subject stands).
```luau
local rig = entity(camId).component.get("cameraRigs.orbital_follow")
rig.verticalLag = 0.4 -- ease stairs and jumps more
rig.recenterDelay = -1 -- keep the heading the player leaves it at
rig:recenter() -- and turn it behind the subject on a button
```
## The camera pulls in when a collider is in the way
Each frame the rig sweeps a sphere of `cameraRadius` from the aim point over the subject itself (`aimHeight` above it, wherever the framed point lags) out to where its framing puts the camera, and stands the camera where the sphere first meets a collider. Every collider in the world stops that sweep, whether or not anything draws it: an invisible walk bound (a `BoxCollider` with no `Model`), a trigger volume and a solid wall all pull the camera in alike. The follow subject is the one entity the sweep passes by default.
The pull-in never cuts. Sweeps of that line ahead, from where the subject is moving to and along where the line is turning over the next 0.8 s, bring the camera in ahead of a wall end or a pillar about to come between it and the subject, at the speed that has it clear when the line gets there; only something no sweep could see coming (a wall that appears) brings it in on the frame it blocks the view, so no frame is drawn from behind geometry. The camera stands no nearer the sweep's start than 0.4 m while there is room round it: when the line has less room than that (the subject against a wall or a pillar the camera is behind), the camera turns round the subject about its up to the nearest turn that has the room, keeps looking the way its framing looks, and turns back onto the line once the line has the room again. A start touching a collider is swept with a thinner sphere, which slides along it, a start nearer it than the thinnest sphere has room for by a ray, and a start inside one holds the camera as far out as it stood.
So a camera that snaps in close to the player, or collapses onto it, while nothing visible stands behind the player is meeting a collider nobody can see. Two fields settle it:
- `cameraIgnore` lists the entities whose colliders the camera sees through. Name the walk bounds and gameplay volumes there and the sweep passes them as it passes the subject, while walls the player can see still pull the camera in. Each entry is an entity (or its id), and it is the collider's own entity that is listed.
- `cameraRadius = 0` turns the pull-in off: the camera stands where its framing puts it, through every collider.
```luau
local rig = entity(camId).component.get("cameraRigs.orbital_follow")
rig.cameraIgnore = { entity.find("NorthBound"), entity.find("SouthBound") }
-- or drop the pull-in entirely
rig.cameraRadius = 0
```
## Thin occluders and the subject's body fade instead of filling the view
In play the camera fades what would otherwise fill the view in place of the subject. A thin occluder (a pillar, a pole, a post, a railing, a doorframe's jamb, a tree trunk: a collider no wider than `occluderFadeWidth` across the line from the camera to the subject at its narrowest, and no deeper along it) does not pull the camera in: the sweeps pass it, and while it stands between the camera and the subject it fades to `occluderFade`, that share of its pixels left undrawn in a screen-space dither so the subject shows through. Walls, floors and every collider wider or deeper than that still pull the camera in, as above. The subject's own body fades as the camera comes within `bodyFadeDistance` of the aim point, reaching `bodyFade` at the nearest the camera stands (0.4 m), so a camera pulled in against a wall shows what lies past the subject rather than the back of its head. Each fade eases in and out over `fadeTime`, never in one frame.
A fade covers the entity and its descendants, in this engine's own views (each player's camera sets its own), and shadows stay whole. `fadeIgnore` lists entities the camera never fades: they pull it in whatever their size. `occluderFade = 0` brings back the pull-in for every collider, and `bodyFade = 0` keeps the body drawn whole. `rig:fading()` reports what the camera fades this frame, and `renderer.drawStats().cameraFaded` how many renderables carry a fade.
```luau
local rig = entity(camId).component.get("cameraRigs.orbital_follow")
rig.fadeIgnore = { entity.find("GateLever") } -- a lever the player must always see
rig.occluderFade = 0 -- or pull in for every collider
```
## Attach through `Camera.behavior`
The Camera owns the behavior slot, so assigning the rig there is what lets the Camera tell it when `follow` changes. A rig added straight onto the entity with `component.add` still poses, but the Camera does not know about it and a `follow` assigned afterwards will not reach it.
## Player cameras: leave `follow` unset
Entering play drops and respawns `PlayerPrototype` subtrees, so the body is recreated with a NEW entity id. A `follow` authored on the rig keeps pointing at the original, which is no longer live, and the camera freezes at its last pose instead of tracking the player.
For a player camera, set the target on the **Camera** and leave the rig's own `follow` empty:
```luau
entity(rigId).component.get("Camera").follow = body -- PlayerPrototype rebinds this on every spawn
```
`PlayerPrototype` refreshes `Camera.follow` to the live body each time it clones, and the rig reads that slot whenever its own `follow` is empty. Set the rig's `follow` only for a camera that watches a fixed, non-respawning subject.
# MovementState
Component that exposes movement state for controller-driven animation and gameplay consumers.
# 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".
# statedWalk
How a body reads the walk its character's mover states, and which way that
walk turns it. `Locomotion` and `LocomotionFull` both read it through here, and
the engine running Locomotion's graph reads it by the same rule.
Each frame it moves a character, the `CharacterController` states its own walk
across what it stands on (its motion less the carry of the ground under it)
and the walk it was asked for (`__poseProgram.stateWalk`). A frame something
else moves the character (a script, a path, a teleport) states none, and the
body's motion that frame is its mover's velocity; a body with no mover of its
own (an NPC body under the root its brain and navigation move) measures its
motion in the world.
## Exports
- `StatedWalk.motion(body, ms, cc, measured, dt) -> (vx, vy, vz, askedX?, askedZ?)`:
this frame's motion across the frame `body` stands in: the stated walk
whenever a mover states one, else the velocity of the entity's
MovementState, else of its CharacterController, else the motion measured in
the world (`measure`); the velocity along up; and the walk asked for, nil
when nothing stated one.
- `StatedWalk.measured() -> Measured`: a fresh record of a body's measured
motion, which the component animating the body keeps.
- `StatedWalk.measure(body, measured, dt) -> (vx, vy, vz)`: the body's world
position's step since the frame before over the frame's gameplay seconds,
across its standing frame. A step faster than `StatedWalk.TELEPORT_SPEED`
(150 m/s) is a placement and leaves the velocity as it was.
- `StatedWalk.isPlacement(dx, dy, dz, dt) -> boolean`: whether a step over
`dt` seconds is faster than `StatedWalk.TELEPORT_SPEED`.
- `StatedWalk.placesCharacter(dx, dy, dz, dt) -> boolean`: whether a move
something else gave a character over a frame placed it rather than carried
it: a move faster than `StatedWalk.TELEPORT_SPEED`, or one longer than
`StatedWalk.PLACEMENT_DISTANCE` (2.5 m) over a frame of any length. The
character controller starts a placed character at rest, with no footing to
jump from until it stands again.
- `StatedWalk.read(body, hasOwnMover) -> (walkX, walkZ, askedX, askedZ)?`: this
frame's stated walk across the frame `body` stands in. A body with a mover
of its own (a MovementState or a CharacterController on its entity) reads
its entity's statement; one with none reads the nearest ancestor's. Nil
when nothing states a walk for it.
- `StatedWalk.facing(vx, vz, askedX, askedZ, moveDeadzone) -> (dirX, dirZ)?`:
the direction a body turns toward: the walk asked for at any speed, else the
velocity once it is faster than `moveDeadzone`. Nil when the body keeps its
facing.
- `StatedWalk.moversChanged(body)`: tells the `Locomotion` and `LocomotionFull`
on `body` that a MovementState or a CharacterController came to its entity
or went from it, so each reads its movers again.
# WASDInput
Action-to-input-bus driver. Reads the `move` axis and `jump` action
each frame, remaps `move` to the active viewport camera's
forward/right basis (via `camera.main()` + `entity(camId).transform.forward`),
and writes the resulting world-space horizontal velocity to a target
component's input fields:
- `target.inputX`, `target.inputZ` — world-space velocity × speed
- `target.inputJump` — boolean, true while the jump action is held
Defaults to writing to `CharacterController` on the same entity, but
the field names are the contract — any component that exposes
`inputX/inputZ/inputJump` is a valid sink (vehicles, hovercraft,
custom CCs).
## Why generic
Independent of which camera is active and independent of the visual
layer:
- Works with any camera (third-person, top-down, FPS, fixed, vehicle).
- Works with no camera (falls back to world-axis WASD).
- Works without `Locomotion` or any animation system — CC moves,
visualization is opt-in.
- Works without a follow rig — `camera.main()` is the seam, not a
specific camera component.
## Public fields
| Field | Default | Purpose |
|---|---|---|
| `speed` | `5.0` | Multiplier on the unit-length input vector |
| `targetComponent` | `"CharacterController"` | Component to write `inputX/inputZ/inputJump` onto |
A custom control scheme is authored as an inputMap that rebinds the
`move` axis and `jump` action — not per-instance key fields on this
component.
## Example
```lua
-- Player with CC + WASDInput + any camera
entity(playerId).component.add("CharacterController")
entity(playerId).component.add("WASDInput")
-- Active viewport camera (any kind)
local cam = entity.spawn("cam", { parent = playerId })
cam.component.add("Camera", { fov = 60, priority = 0 })
cam.component.add("orbital_follow", { follow = playerId })
-- Press W → CC.inputX/inputZ are written camera-relative each frame
-- → CC translates the body → MovementState reports velocity →
-- (optional) Locomotion rotates the visible mesh + plays anims.
```
# bodyFacing
> 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.
Which way a character's body visibly faces, by the one rule every reader of
that facing shares. `Locomotion` and `LocomotionFull` resolve the anchor they
turn through here, and `CameraRig.visibleForward` reads the facing through
here, so a follow camera binding behind a character reads the anchor the
component turns, whichever component animates it and however the character's
children are ordered (a body swapped in by `setCharacter` stands after the
avatar's name label).
The rotation anchor is the topmost direct child of the entity the component
sits on whose subtree holds the rigged skeleton, else that entity itself when
it carries a Skeleton. Each component declares which way along the anchor the
body faces: `Locomotion.forward` is a direction in the anchor's local frame
(`{0, 0, -1}` by default, the -Z every composed avatar body faces along), and
`LocomotionFull.faceSign` names the anchor's -Z (`1`) or +Z (`-1`).
How a body file is composed under the anchor so it faces the anchor's -Z,
measured from its skeleton, is `@builtin::modules.bodyFacing`.
## Exports
- `BodyFacing.COMPONENTS`: `{ "Locomotion", "LocomotionFull" }`, the
components that turn a body, in the order a character carrying both reads
them.
- `BodyFacing.isRigged(entityId) -> boolean`: the entity carries a Skeleton
whose rig has hydrated (bones present).
- `BodyFacing.body(entityId) -> string?`: the skinned body, the entity itself
when rigged, else its first rigged descendant.
- `BodyFacing.anchor(entityId) -> string?`: the rotation anchor of the
character the facing component sits on.
- `BodyFacing.heldAnchor(entityId) -> string?`: the anchor as `anchor`
resolves it, kept from one read to the next while it still stands as the
entity or one of its direct children, and resolved again once it has gone,
so a reader asking every frame walks the body's subtree once.
- `BodyFacing.declared(componentName, component) -> (x, y, z)`: the
anchor-local direction a facing component declares.
- `BodyFacing.declaring(targetId) -> (id?, componentName?, component?)`: the
subject or the nearest ancestor carrying a facing component.
- `BodyFacing.forward(targetId) -> (x?, y?, z?)`: the world-space direction
the body faces, read through `heldAnchor`, nil when nothing up the chain
turns the subject.
- `BodyFacing.source(targetId) -> string?`: what `forward` reads the facing
from (the declaring entity, the component, the anchor and the anchor-local
direction it declares), as one key that changes when a facing component
arrives or goes, when what it declares changes (`Locomotion.forward`,
`LocomotionFull.faceSign`) or when a body stands up under the character,
and holds while the body turns; nil when nothing up the chain turns the
subject.
```luau
local BodyFacing = require("characterController.characterController.movement.bodyFacing")
local fx, fy, fz = BodyFacing.forward(characterId)
```
# 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).
# 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
```
# characterController
The character controller of the Controllers world. `CharacterController`
moves a character with capsule casts: walking, running and jumping, coyote time,
slopes, steps, moving platforms, carrying, pushing and swimming. `MovementState`
states the motion its animation reads, and `Locomotion` (or the 87-clip
`LocomotionFull`) plays the Synty Polygon Masculine clips this package holds
from it. `WASDInput` drives a controller from the keyboard, and the
`characterController` toolbox installs the set on an entity.
`CharacterController` carries the `bodyMover` and `playerDefault` tags and
`MovementState` carries `playerDefault`, so a default player authored once the
package is installed walks with them. The player's controls drive the
character once it is bound as the local player's body
(`layers.active.players.localPlayer.avatar = entity(id)`); any other
character moves on what writes its `CharacterController` input bus.
Installed as `@controllers` (`world.installLibrary({ world =
"034d26cf-dc3d-4123-abad-3944f97c6a60", as = "controllers" })`), its assets are
`characterController.<name>`.
## Layout
```
characterController.package/
CharacterController.component -- the mover
MovementState.component -- the motion the animation reads
Locomotion.component -- blend-space animation (synty preset)
LocomotionFull.component -- the 87-clip variant (synty_full preset)
WASDInput.component -- keyboard drive of a controller's input bus
AnimDebug.component -- an overlay of the controller's state
characterController.module/ -- install / uninstall / preset, and the
-- collision and movement helpers
presets/ -- feel presets and the Synty clip presets
files/synty/ -- the Synty body and its animation clips
inputMaps/flight.inputMap -- flyUp / flyDown for a flying player
tools/characterController.toolbox/ -- install and uninstall tools
documentation/ -- 01-overview to 05-launch-and-knockback
```
## Flow
```
┌────────────────────┐
user / agent ──┤ characterController│
│ .toolbox │
└────────────────────┘
│
▼
┌──────────────────────┐
custom code ──────┤ characterController │── install /
(require) │ .module (API) │ uninstall / preset
└──────────────────────┘
│
▼
┌────────────────────────┐
│ CharacterController │
│ + Locomotion │
│ + MovementState │
│ + AnimDebug │
│ (+ third-person cam) │
└────────────────────────┘
│
▼
WASD-driven character with animation
on any entity, no hand wiring required.
```
`characterController.install(entity, opts)` is the only thing most callers
need — it adds the controller, the locomotion graph, the movement-state
mirror, and (optionally) a third-person camera child. The package is
self-contained: it depends only on standard utility modules and on the
animation graph engine, never on game-specific code.
## The engine's locomotion contract
`Locomotion` and `LocomotionFull` carry the `locomotion` tag in their
`.metadata`, and the `synty`, `synty_full` and `humanoid` presets carry it as
clip sets for them. The engine reaches a body's locomotion through that tag
(`@builtin::modules.api.engine.body_locomotion`): an avatar's composition
states the way its body faces, a body swap rebuilds its graph, and the avatar's
animator, a headset body and a carried prop read its facing. The `synty`
preset also carries `playerDefault`: it is the clip set every humanoid avatar
in a world holding this package animates with when it names none.
## Documentation
- [`documentation/01-overview.md`](documentation/01-overview.md) — what
this package is and when to reach for it.
- [`documentation/02-install.md`](documentation/02-install.md) — the
`characterController.install(id, opts)` recipe.
- [`documentation/03-presets.md`](documentation/03-presets.md) —
shipped presets (synty, default humanoid) and authoring your own.
- [`documentation/04-customize.md`](documentation/04-customize.md) —
overriding components, swapping the camera, custom blend spaces.
# cameraRigs
> 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.
Camera behaviors for games: a `Camera` names one in its `behavior` field and
the behavior moves and turns the camera every frame. Each carries the
`cameraBehavior` tag, so `layers.active.camera.behaviors` lists it once the
package is installed, and `orbital_follow` carries `playerDefault`, which makes
it the camera a default player is authored with.
| Behavior | What it does |
|---|---|
| `orbital_follow` | Orbits the player on three rings (low, middle, high); look turns it, the wheel zooms, and it pulls in past walls. |
| `third_person_follow` | An over-the-shoulder camera that sits behind the player and turns back behind them while they walk. |
| `first_person` | The camera at the player's eyes; seats in a `FirstPersonBody`. |
| `chase` | Trails a moving body from behind and above: a car, a boat, a runner. |
| `mount` | Rides a seat on a body: a cockpit, a hood, a turret sight. |
| `rts` | A strategy camera that pans, rotates and zooms over a map. |
| `isometric` | A fixed-angle isometric camera that pans and follows. |
| `birds_eye` | Looks straight down from overhead. |
| `orbit` | Orbits a point or an entity under the look and zoom controls. |
| `side_scroller` | Holds a 2.5D side view on a target. |
| `cinematic` | Plays a cutscene path. |
| `menu` | Holds the camera's authored pose. |
`camera_rig` is the module the follow cameras share (follow, trail, pull-in,
fades, recentring). The `cameraRig` input map binds move, look and zoom for the
`rts`, `isometric`, `birds_eye`, `orbit`, `chase` and `mount` behaviors; the
follow cameras read `@builtin::inputMaps.default`.
```luau
local cam = entity.spawn("cam")
cam.component.add("Camera", { behavior = asset.ref("cameraRigs.chase", "component") })
cam.component.get("cameraRigs.chase").target = car.id
```
`documentation/choosing-a-camera` says which behavior fits which game and the
fields each one reads. Every behavior runs looks through the player's own camera
settings (`@builtin::modules.api.engine.camera_settings`).