Skip to main content

Controllers

A controller is a higher-level tool computing the motion of a body from what your application asks for, rather than leaving it entirely to the forces of the simulation. Rapier provides:

Character controller​

Most games involve bodies behaving in ways that defy the laws of physics: floating platforms, elevators, playable characters, etc. This is why kinematic bodies exist: they offer a total control over the body’s trajectory since they are completely immune to forces or impulses (like gravity, contacts, joints).

But this control comes at a price: it is up to the user to take any obstacle into account by running custom collision-detection operations manually and update the trajectory accordingly. This can be very difficult. Detecting obstacles usually rely on ray-casting or shape-casting, used to adjust the trajectory based on the potential contact normals. Often, multiple ray or shape-casts are needed, and the trajectory adjustment code isn’t straightforward.

The Kinematic Character Controller (which we will abbreviate to character controller) is a higher-level tool that will emit the proper ray-casts and shape-casts to adjust the user-defined trajectory based on obstacles. The well-known move-and-slide operation is the main feature of a character controller.

note

Despite its name, a character controller can also be used for moving objects that are not characters. For example, a character controller may be used to move a platform. In the rest of this guide, we will use the word character to designate whatever you would like to move using the character controller.

Rapier provides a built-in general-purpose character controller implementation. It allows you to easily:

  • Stop at obstacles.
  • Slide on slopes that are not to steep.
  • Climb stairs automatically.
  • Walk over small obstacles.
  • Interact with moving platforms.

Despite the fact that this built-in character controller is designed to be generic enough to serve as a good starting point for many common use-cases, character-control (especially for the player’s character itself) is often very game-specific. Therefore the builtin character controller may not work perfectly out-of-the-box for all game types.

Setup and usage​

A new character controller can be created and removed by the physics World:

// The gap the controller will leave between the character and its environment.
let offset = 0.01;
// Create the controller.
let characterController = world.createCharacterController(offset);
// Remove the controller once we are done with it.
world.removeCharacterController(characterController);

Note that the character controller does not store a reference to the rigid-body and collider it controls. Therefore, the same instance of the CharacterController class can be used to control different colliders. This can be useful if you want to apply the same kind of character control settings to multiple characters.

The created character controller can then be used to control the movement of a collider taking into account obstacles on its path. This is done in two steps:

  1. Given a desired translation, compute the actual translation that we can apply to the collider based on the obstacles.
  2. Read the result and apply it to the rigid-body or collider (if it isn’t attached to a rigid-body) by setting its position, kinematic velocity, or next kinematic position, depending on the situation.
let characterController = world.createCharacterController(offset);
characterController.computeColliderMovement(
collider, // The collider we would like to move.
desiredTranslation, // The movement we would like to apply if there wasn’t any obstacle.
);
// Read the result.
let correctedMovement = characterController.computedMovement();
// TODO: apply this corrected movement by following the rules described below.

The recommended way to update the character’s position depends on its representation:

  • A collider not attached to any rigid-body: set the collider’s position directly (with collider.setTranslation) to the corrected movement added to its current position.
  • A velocity-based kinematic rigid-body: set its velocity (with rigidBody.setLinvel) to the computed movement divided by the timestep length.
  • A position-based kinematic rigid-body: set its next kinematic position (with rigidBody.setNextKinematicTranslation) to the corrected movement added to its current position.
info

The character’s shape may be any shape supported by Rapier. However, it is recommended to either use a cuboid, a ball, or a capsule since they involve less computations and less numerical approximations.

warning

The built-in character controller does not support rotational movement. It only supports translations.

Character offset​

For performance and numerical stability reasons, the character controller will attempt to preserve a small gap between the character shape and the environment. This small gap is named offset and acts as a small margin around the character shape. A good value for this offset is something sufficiently small to make the gap unnoticeable, but sufficiently large to avoid numerical issues (if the character seems to get stuck inexplicably, try increasing the offset).

character offset

// Here the character controller is initialized with an offset of 0.01.
let offset = 0.01;
let characterController = world.createCharacterController(0.01);
warning

It is not recommended to change the offset after the creation of the character controller.

Up vector​

The up vector instructs the character controller of what direction should be considered vertical. The horizontal plane is the plane orthogonal to this up vector. There are two equivalent ways to evaluate the slope of the floor: by taking the angle between the floor and the horizontal plane (in 2D), or by taking the angle between the up-vector and the normal of the floor (in 2D and 3D). By default, the up vector is the positive y axis, but it can be modified to be any (unit) vector that suits the application.

up vector and slope angles

let characterController = world.createCharacterController(0.01);
// Change the character controller’s up vector to the positive X axis.
characterController.setUp({ x: 1.0, y: 0.0 });

Slopes​

If sliding is enabled, the character can automatically climb slopes if they are not too steep, or slide down slopes if they are too steep. Sliding is configured by the following parameters:

  • The max slope climb angle: if the angle between the slope to climb and the horizontal floor is larger than this value, then the character won’t be able to slide up this slope.
  • The min slope slide angle: if the angle between the slope and the horizontal floor is smaller than this value, then the vertical component of the character’s movement won’t result in any sliding.
info

As always in Rapier, angles are specified in radians.

let characterController = world.createCharacterController(0.01);
// Don’t allow climbing slopes larger than 45 degrees.
characterController.setMaxSlopeClimbAngle(45 * Math.PI / 180);
// Automatically slide down on slopes smaller than 30 degrees.
characterController.setMinSlopeSlideAngle(30 * Math.PI / 180);

Stairs and small obstacles​

If enabled, the autostep setting allows the character to climb stairs automatically and walk over small obstacles. Autostepping requires the following parameters:

  • The maximum height the character can step over. If the vertical movement needed to step over this obstacle is larger than this value, then the character will be stopped by the obstacle.
  • The minimum (horizontal) width available on top of the obstacle. If, after the character is teleported on top of the obstacle, it cannot move forward by a distance larger than this minimum width, then the character will just be stopped by the obstacle (without being moved to the top of the obstacle).
  • Whether or not autostepping is enabled for dynamic bodies. If it is not enabled for dynamic bodies, the character won’t attempt to automatically step over small dynamic bodies. Disabling this can be useful if we want the character to push these small objects (see collisions) instead of just stepping over them.

The following depicts (top) one configuration where all the autostepping conditions are satisfied, and, (bottom) two configurations where these conditions are not all satisfied (left: because the width of the step is too small, right: because the height of the step is too large):

autostepping

info

Autostepping will only activate if the character is touching the floor right before the obstacle. This prevents the player from being teleported on to of a platform while it is in the air.

let characterController = world.createCharacterController(0.01);
// Autostep if the step height is smaller than 0.5, its width is larger than 0.2,
// and allow stepping on dynamic bodies.
characterController.enableAutostep(0.5, 0.2, true);
// Disable autostep.
characterController.disableAutostep();

Snap-to-ground​

If enabled, snap-to-ground will force the character to stick to the ground if the following conditions are met simultaneously:

  • At the start of the movement, the character touches the ground.
  • The movement has a slight downward component.
  • At the end of the desired movement, the character would be separated from the ground by a distance smaller than the distance provided by the snap-to-ground parameter.

If these conditions are met, the character is automatically teleported down to the ground at the end of its motion. Typical usages of snap-to-ground include going downstairs or remaining in contact with the floor when moving downhill.

snap-to-ground

let characterController = world.createCharacterController(0.01);
// Snap to the ground if the vertical distance to the ground is smaller than 0.5.
characterController.enableSnapToGround(0.5);
// Disable snap-to-ground.
characterController.disableSnapToGround();

Filtering​

It is possible to let the character controller ignore some obstacles. This can be achieved by setting the optional arguments of the KinematicCharacterController.computeColliderMovement method:

  • filterFlags: to exclude whole families of obstacles (e.g. all the colliders attached to dynamic rigid-bodies).
  • filterGroups: filter based on the colliders collision groups.
  • filterPredicate: an arbitrary closure to filter-out colliders based on user-defined rules.

Collisions​

As the character moves along its path, it will hit grounds and obstacles before sliding or stepping on them. Knowing what collider was hit on this path, and where the hit took place, can be valuable to apply various logic (custom forces, sound effects, etc.) This is why a set of character collision events are collected during the calculation of its trajectory.

info

The character collision events are given in chronological order. For example, if, during the resolution of the character motion, the character hits an obstacle A, then slides against it, and then hits another obstacle B. The collision with A will be reported first, and the collision with B will be reported second.

let characterController = world.createCharacterController(0.01);
characterController.computeColliderMovement(collider, desiredMovementVector);

// After the collider movement calculation is done, we can read the
// collision events.
for (let i = 0; i < characterController.numComputedCollisions(); i++) {
let collision = characterController.computedCollision(i);
// Do something with that collision information.
}

Unless dynamic bodies are filtered-out by the character controller’s filters, they may be hit during the resolution of the character movement. If that happens, these dynamic bodies will generally not react to (i.e. not be pushed by) the character because the character controller’s offset prevents actual contacts from happening.

In these situations forces need to be applied manually to this rigid-bodies. The character controller can apply these forces for you if needed:

let characterController = world.createCharacterController(0.01);
// Enable the automatic application of impulses to the dynamic bodies
// hit by the character along its path.
characterController.setApplyImpulsesToDynamicBodies(true);

Gravity​

Since you are responsible for providing the movement vector to the character controller at each frame, it is up to you to emulate gravity by adding a downward component to that movement vector.

Vehicle controller​

Simulating a car with rigid-bodies and joints, for example using one rigid-body per wheel attached to the chassis by a joint, is possible but can be difficult to control for games requiring non-realistic vehicles. This is why Rapier provides a vehicle controller (the current implementation was ported from the btRaycastVehicle of Bullet). The vehicle is a single rigid-body modeling its chassis, and its wheels are only represented by ray-casts pushing that body along a spring-like suspension.

Setup​

The chassis is created like any other dynamic rigid-body, and the wheels are added to the controller afterwards. Each wheel is given its position on the chassis, the direction of its suspension (the direction of its ray-cast), its axle, the rest length of its suspension, and its radius. The WheelTuning shared by the wheels is what makes the vehicle feel heavy or light by controlling the elastic properties (stiffness and damping) of the suspension, as well as the grip of the wheels:

// The chassis is an ordinary dynamic rigid-body.
let hw = 0.3;
let hh = 0.15;
let chassis = world.createRigidBody(
RAPIER.RigidBodyDesc.dynamic().setTranslation(0.0, 1.0, 0.0),
);
world.createCollider(RAPIER.ColliderDesc.cuboid(hw * 2.0, hh, hw).setDensity(100.0), chassis);

let vehicle = world.createVehicleController(chassis);
let wheelPositions = [
{ x: hw * 1.5, y: -hh, z: hw }, { x: hw * 1.5, y: -hh, z: -hw },
{ x: -hw * 1.5, y: -hh, z: hw }, { x: -hw * 1.5, y: -hh, z: -hw },
];

for (let position of wheelPositions) {
// The position of the wheel, the direction its suspension pushes along, its axle, the
// rest length of its suspension, and its radius; all in the local frame of the chassis.
vehicle.addWheel(position, { x: 0.0, y: -1.0, z: 0.0 }, { x: 0.0, y: 0.0, z: 1.0 }, hh, hh / 4.0);
}

// The tuning of each wheel: its suspension and its grip.
for (let i = 0; i < vehicle.numWheels(); ++i) {
vehicle.setWheelSuspensionStiffness(i, 100.0);
vehicle.setWheelSuspensionCompression(i, 10.0);
vehicle.setWheelSuspensionRelaxation(i, 10.0);
}

Driving the vehicle​

A vehicle is driven by giving each of its wheels an engine force, a brake force, and a steering angle. The controller is then updated before each timestep, which is when the ray-casts are made and when the resulting suspension and friction forces are applied to the chassis. It is strongly recommended to exclude the chassis from the ray-casts, otherwise the ray might hit it and be misinterpreted as being the floor.

for (let k = 0; k < 200; ++k) {
// The vehicle is driven by setting the engine force, the brake, and the steering angle of
// its wheels. Here the two front wheels are the driving and steering ones.
vehicle.setWheelEngineForce(0, 30.0);
vehicle.setWheelSteering(0, 0.2);
vehicle.setWheelEngineForce(1, 30.0);
vehicle.setWheelSteering(1, 0.2);

// The wheels are ray-casted against the scene: the dynamic bodies, including the chassis
// itself, are generally excluded from these ray-casts.
vehicle.updateVehicle(world.integrationParameters.dt, RAPIER.QueryFilterFlags.EXCLUDE_DYNAMIC);
world.step();
}

console.log("Vehicle speed:", vehicle.currentVehicleSpeed());
note

The state of each wheel after an update (whether it touches the floor, the compression of its suspension, its rotation angle, etc.) is readable from the controller. This is what the rendering of the wheels can be based on since there is no actual per-wheel rigid-bodies to read their state from.

PID controller​

It is generally not recommended to move a rigid-body by setting its pose directly: teleporting it would ignore every obstacle on the way. The recommended alternative is generally to push it with a force (or an impulse) that is strong enough to reach the target. However, pushing with a single constant force/impulse will generally overshoot the target. Thus, ideally, the force or impulse should be carefully selected and updated each frame as the rigid-body gets closer to its target.

This is what a PID controller (Proportional-Integral-Derivative) is designed to calculate: given the target pose, it computes the ideal velocity change bringing the body closer to it. This is the building block of the velocity-based character controllers, but it is useful for anything that must follow a target without being teleported: a dynamic moving platform, an object held by the player, a following camera, etc.

info

The gains of the controller are what makes it reach its target quickly or smoothly. The proportional gain is applied to the position errors and is usually set to a multiple of the inverse of the timestep length (e.g. 6060 for a timestep of 1/601 / 60 seconds). The derivative gain is applied to the velocity errors and is usually set in [0,1][0, 1], where 00 means no damping and 11 means that the velocity errors are corrected within a single timestep.

The coordinate axes (linear and/or angular) controlled by the controller can be selected in order, for example, to only control the translations of a body while leaving its rotations to the simulation:

// The proportional, integral, and derivative gains of the controller, acting on the linear
// axes only: the body is pushed toward its target without its rotation being controlled.
let pid = world.createPidController(60.0, 0.0, 0.8, RAPIER.PidAxesMask.AllLin);
let target = { x: 3.0, y: 2.0 };

for (let k = 0; k < 200; ++k) {
// The correction is applied to the velocity of the rigid-body.
pid.applyLinearCorrection(body, target, { x: 0.0, y: 0.0 });
world.step();
}