Log inGet started
Package

CharacterController.component

Newest version

This package holds more than this page lists. See all of its files in its world.

README.md

CharacterController

Kinematic mover. Integrates velocity against gravity, walls, ceilings and ground, and writes the result to the entity's position every frame.

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:

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.

  • 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.
  • 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:

-- 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.
  • 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:

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" }):

preset.apply("@builtin::systems.characterController.presets.weighty",
    { entity = id, component = "CharacterController" })
PresetGroundJump
instantno ramp: starts, stops and turns the frame it is askedjumpForce against gravity, full height however it is pressed, no fall scaling or cap
responsive40 m/s² up, 50 m/s² braking: quick and crisp1.3 m in 0.38 s, let go at take-off 0.25 m, falls at 1.6x, capped at 20 m/s
weighty6 m/s² up, 6 m/s² braking: a heavy body that commits to its heading0.8 m in 0.36 s, full height every press, falls at 2x, capped at 25 m/s, little air control
floaty25 m/s² up, 15 m/s² braking: light, slides a little into stops2.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:

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

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.

    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) stands where it was put and rides nothing until it stands on a body again.

    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.

    player.component.add("CapsuleCollider", { isTrigger = true, contactTag = "player" })
    Physics.setContactFilter("player", "ghostWall", "ignore")
    

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):

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.
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.
  • 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:

local s = entity(id).component.get("CharacterController"):stats()
print(s.resting, s.stepFrames, s.restFrames)