Character Controller
Updated
The Character Controller (comp-character-controller) is the character: a capsule-shaped body that walks, runs, jumps, falls, climbs steps and slides along walls, turning to face where it goes. The player’s controls, AI and scripts all move a character through this one component, on desktop, touch, gamepad and VR. You use it for the player in first or third person, and for any non-player character that walks.
Before you start
Section titled “Before you start”- Cameras look and the Character Controller moves. Read Camera controllers to pair it with a view.
- The capsule lives in the physics world. See Physics for colliders and Physics layers for
collisionLayer. - Its events reach scripts through a Signal Emitter on the same entity. See Events and signals.
Where to put it
Section titled “Where to put it”The Character Controller is offered on cameras, meshes and models, primitives, groups and snap zones.
- First person. Put it on the camera entity, next to a First Person controller. The camera’s origin is its eyes, so hang the capsule below them with a negative
center.y:-0.7puts the eyes at 1.6 m on the default 1.8 m capsule. On a camera the Character Controller never turns the entity: First Person owns the facing. - Third person. Put it on the character that the Third Person controller’s
targetfollows. If the character’s origin is at its feet, setcenter.yto half itsheight. - Non-player characters. Put it on the character and set
controls: false, so the player’s keys do not move it. Drive it from a script, a NavMesh Agent or a Steering Agent.
| Prop | Type | Default | Description |
|---|---|---|---|
controls |
boolean | true |
The player’s controls move it: keys, gamepad, touch and VR. Set false when only AI or a script moves it. |
speed |
number | 4 |
Walk speed, in metres per second. Running is 1.75 times this. |
turnSpeed |
number | 1440 |
How fast it turns to face its travel, in degrees per second. A quarter turn at the default takes about an eighth of a second. 0 turns at once. |
height |
number | 1.8 |
Capsule height, caps included, in metres. At least twice the radius. |
radius |
number | 0.4 |
Capsule radius, in metres. |
center |
{ x, y, z } |
{ x: 0, y: 0, z: 0 } |
Capsule centre from the entity’s origin, in metres. |
slopeLimit |
number | 45 |
Steepest slope it walks up, in degrees. |
collision |
integer | 0 |
The physics layer the capsule is on, 0 to 15. Only colliders on layers it collides with stop it. |
Some values are the same for every character: the player’s jump rises 1.25 m, steps up to 0.3 m are climbed, and running is 1.75 × speed. A facing set by a script or a teleport is kept, so a character jostled in place never spins.
Player controls
Section titled “Player controls”With controls: true, it reads the player’s controls in play:
| Device | Move | Run | Jump | Look and turn |
|---|---|---|---|---|
| Keyboard and mouse | WASD or arrow keys | Hold Shift | Space | The mouse, through the camera controller |
| Gamepad | Left stick | Push it 90% or more | A | Right stick, through the camera controller |
| Touch | A Screen Gamepad’s left stick | Push it 90% or more | Its A button | A finger on the canvas or its right stick |
| VR | Left thumbstick | Push it 90% or more | A on the right controller | The right stick snap-turns 30° |
- Movement is relative to the rendering camera: forward is where the camera looks, flattened onto the ground.
- Sticks are analog with a small dead zone: a light push walks slowly.
- On touch screens, add a Screen Gamepad to the camera. The Character Controller shows no on-screen stick by itself.
- Several Character Controllers with
controls: trueall follow the same controls. Setcontrols: falseon the others. - Jumping needs gravity in the project’s physics settings, and no NavMesh Agent on the entity.
The capsule
Section titled “The capsule”The capsule is a kinematic body moved by the physics character solver:
- it collides and slides along walls, climbs steps, walks up slopes up to
slopeLimitand keeps to the ground over small drops; - it falls with the project’s gravity, and stays upright: only its facing turns;
- it pushes dynamic bodies it walks into, and walks through sensors (triggers);
- it is the entity’s whole physics body: a Rigid Body or colliders on the same entity are not built.
A capsule placed inside the ground or a wall (after a teleport, say) is settled onto the surface, so it never falls through.
Collision events. With a Signal Emitter on the entity, the capsule sends the collider events: PhysicsCollider::intersection-enter and -exit for triggers it walks through, and collision-enter and collision-exit for what it stands on. A wall it walks into is not a contact: it slides along it and sends nothing.
Walking on a navmesh
Section titled “Walking on a navmesh”With an enabled NavMesh Agent on the same entity, the character walks the navmesh instead of the physics world:
- the agent owns the position: the character stays on the navmesh and crosses its links;
moveTofinds a path around walls, at the agent’sspeed;moveand the player’s controls slide it along the navmesh at the character’sspeed;- there is no gravity and no jump; crossing a link shows as the
jumpstate.
On the main camera, the Character Controller carries the VR player: the XR rig stays over the body, so walls stop the player. With controls: true the body follows the headset as the player walks around the room, the left stick moves it and the right stick snap-turns 30°. Spawn points, spot points, travel points and teleports move the body, and the rig follows. See XR.
Scripting
Section titled “Scripting”| Member | What it does |
|---|---|
move(x, z, run?) |
Move this frame toward a world direction: x and z from -1 to 1, scaled by speed (or 1.75 × with run). A partial push walks slower. Call it every frame it should keep going. A non-zero move cancels a moveTo. |
move |
Go to a world position ([x, y, z] or { x, y, z }), an entity’s name or id, or an object (where it is now), and send arrive there. With a NavMesh Agent it pathfinds; otherwise it walks straight and something in the way stops it. Returns false when a name matches nothing or there is no route. |
stop() |
Cancel a moveTo. |
jump(height = 1. |
Jump height metres on the next frame, when grounded. Needs gravity; does nothing on a NavMesh Agent. |
teleport(position, yaw?) |
Put it at a world position at once, optionally facing yaw radians about world Y. Cancels a moveTo and any fall or jump. |
state |
'idle', 'walk', 'run', 'jump' or 'fall'. Read-only. |
isGrounded |
true while resting on a surface, or on the navmesh and not crossing a link. |
destination |
Where an active moveTo is going, { x, y, z }, else undefined. |
velocity |
Its velocity over the last frame, a THREE.Vector3 in metres per second. Read it; do not change it. |
state returns to idle only after a quarter second without moving, so it never flickers. jump is the rise and fall the descent; run comes from the player’s run or from move with run.
Events
Section titled “Events”With a Signal Emitter on the entity:
| Event | Constant | Data | When |
|---|---|---|---|
Character |
Event |
{ state, previous } |
Its state changed. |
Character |
Event |
{ position } |
A moveTo got there. position is { x, y, z }. |
Examples
Section titled “Examples”1. Play an animation for each state
Section titled “1. Play an animation for each state”#pragma lifecycle(startup)
// Map each movement state to a clip name in the character's model.const CLIPS = { idle: 'Idle', walk: 'Walk', run: 'Run', jump: 'Jump', fall: 'Jump' };
function startup() { // The character has a Character Controller, an Animation Clip component // and a Signal Emitter with the signal 'player'. const clips = self.parent.getComponent(AnimationClipComponent);
on('player', (event) => { if (event.eventType !== EventType.CharacterController.StateChange) return; clips.layer(CLIPS[event.data.state])?.play(); });}Every state-change of a Character Controller plays the matching clip of the character's model: Walk while moving and Idle at rest. States without a clip are skipped.
Click the scene, then walk with WASD or the arrow keys: the character switches between its Walk and Idle clips. Drag to look around.
Every time the character starts walking, running, jumping or falling, the controller sends state-change with the new state. The script looks up the matching clip by name with layer(name) and plays it. The optional chaining ?. skips states whose clip the model does not have. See Animation for clips.
2. A chaser that runs at the player
Section titled “2. A chaser that runs at the player”#pragma lifecycle(startup, update)
const STOP_DISTANCE = 2; // metresconst RUN_DISTANCE = 8; // run when farther than this
const me = new THREE.Vector3();const target = new THREE.Vector3();let character;
function startup() { // The chaser has a Character Controller with controls: false. character = self.parent.getComponent(CharacterControllerComponent);}
function update() { const player = CameraDirector.main; if (!player) return; self.parent.getWorldPosition(me); player.getWorldPosition(target);
const x = target.x - me.x; const z = target.z - me.z; const distance = Math.hypot(x, z); if (distance > STOP_DISTANCE) character.move(x / distance, z / distance, distance > RUN_DISTANCE);}A character with a Character Controller and no player controls runs towards the main camera every frame with move, and stops two metres short.
Drag to orbit the camera around the yard: the chaser turns and runs after you, and stops when it is close. Scroll to zoom.
Each frame the script finds the flat direction from the chaser to the player and divides it by the distance, giving a direction of length 1. move walks that way this frame and turns the chaser to face it; the third argument makes it run while the player is far away. Once within two metres it stops calling move, and the character comes to rest. The two vectors are created once and reused, so nothing is allocated per frame.
3. Jump pads and a high jump
Section titled “3. Jump pads and a high jump”#pragma lifecycle(startup, update)
const PAD_HEIGHT = 4; // metresconst HIGH_JUMP = 2.5; // metreslet character;
function startup() { // On the player's character, with a Character Controller and a Signal Emitter 'player'. character = self.parent.getComponent(CharacterControllerComponent);
on('player', (event) => { if (event.eventType !== EventType.PhysicsCollider.IntersectionEnter) return; const pad = findEntity(event.data.otherEntityId || ''); if (pad && pad.name.startsWith('Jump Pad')) character.jump(PAD_HEIGHT); });}
function update() { // E jumps higher than the built-in 1.25 m jump on Space. if (character.isGrounded && Input.keyboard.isKeyReleased(Key.E)) { character.jump(HIGH_JUMP); }}The player's Character Controller reports the sensor pads it walks into: a pad named Jump Pad launches it 4 m up, and E jumps higher than the built-in jump on Space.
Click the scene, then walk with WASD onto a green pad to be launched. Press E for a high jump and Space for the normal one. Drag to look around.
Jump pads are entities with a sensor collider (a trigger) whose names start with Jump Pad. When the capsule walks into one, it sends intersection-enter with the pad’s id in event.data.otherEntityId, and the script launches the player 4 m up with jump(PAD_HEIGHT). In update, the E key asks for a higher jump. It uses E rather than Space because Space already triggers the built-in jump. jump only acts when the character is grounded; the script checks isGrounded itself so the intent is clear.
4. Patrol between waypoints
Section titled “4. Patrol between waypoints”#pragma lifecycle(startup, update)
const POSTS = ['Post A', 'Post B', 'Post C'];let guard;let next = 0;let walking = false;
function startup() { guard = self.parent.getComponent(CharacterControllerComponent); on('guard', (event) => { if (event.eventType === EventType.CharacterController.Arrive) { walking = false; log('Reached', POSTS[(next - 1) % POSTS.length]); } });}
function update() { if (walking) return; if (guard.moveTo(POSTS[next % POSTS.length])) { walking = true; next++; }}A guard with a Character Controller walks from post to post: moveTo starts each leg and the controller's arrive event ends it.
Watch the guard walk between the grey posts. Drag to orbit the camera, scroll to zoom.
moveTo accepts an entity name and walks there, sending arrive on arrival. The script starts the next leg only when the previous one has arrived. If moveTo returns false (the target is missing, or with a NavMesh Agent the navmesh is not ready yet), the script simply tries again next frame. Add a NavMesh Agent to the guard and the same script pathfinds around walls.
5. Respawn after a fall
Section titled “5. Respawn after a fall”#pragma lifecycle(startup, update)
const KILL_HEIGHT = -20;const START = { x: 0, y: 1, z: 6 };const here = new THREE.Vector3();let character;
function startup() { character = self.parent.getComponent(CharacterControllerComponent);}
function update() { self.parent.getWorldPosition(here); if (here.y < KILL_HEIGHT) { character.teleport(START, Math.PI); // half a turn about world Y emit('player/respawned'); }}A player walking off a floating platform falls until it is 20 m down, then teleport puts the Character Controller back at the start, turned half a turn, with its fall cancelled.
Click the scene, then walk off the edge of the platform with WASD: after the fall you are back at the start. Drag to look around.
This script is on a third-person character. If the character falls off the world, teleport puts the capsule back at START at once, turned to a yaw of Math.PI radians (half a turn), and cancels the fall so it does not keep its downward speed. A Third Person camera following the character comes along by itself.
Common mistakes
Section titled “Common mistakes”- Adding a Rigid Body as well. The capsule is the whole body; a Rigid Body or colliders on the same entity are not built.
- The player sinks into the floor or floats. Fix
center: negative on a camera whose origin is the eyes,height / 2on a model whose origin is at its feet. - Two characters move together. Both have
controls: true. Setcontrols: falseon the ones the player does not drive. - Calling
moveonce.movelasts one frame; call it inupdateevery frame the character should keep going. - Jump does nothing. It needs gravity, the ground under the character, and no NavMesh Agent.
- Moving the entity’s position directly. Writing
entity.positiondoes not move the capsule. Useteleport,moveormoveTo. - Networked characters. Only the client that owns a networked character moves it; see Multiplayer.