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. Don’t hesitate to copy and customize it to fit your particular needs.

Setup and usage#

There are two ways to use the character-controller with bevy_rapier: using the KinematicCharacterController component or using the RapierContext::move_shape method. The component approach is more convenient, but the move_shape approach can be slightly more flexible in terms of filtering.

note

Refer to the API documentation of RapierContext::move_shape for details on how to use it.

The KinematicCharacterController component must be added to the same entity as a TransformBundle bundle. If the field KinematicCharacterController::custom_shape isn’t set, then the entity it is attached to must also contain a Collider component. That collider optionally be attached to a rigid-body. At each frame, the KinematicCharacterController::translation field can be set to the desired translation for that character.

During the next physics update step, that translation will be resolved against obstacles, and the resulting movement will be automatically applied to the entity’s transform, or the transform of the entity containing the rigid-body the collider to move is attached to.

The applied character motion, and the information of whether the character is touching the ground at its final position, can be read with the KinematicCharacterControllerOutput component (inserted automatically to the same entity as the KinematicCharacterController component).

fn init_system(mut commands: Commands) {
command.spawn()
.insert(RigidBody::KinematicPositionBased)
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController::default());
}
fn update_system(mut controllers: Query<&mut KinematicCharacterController>) {
for mut controller in controllers.iter_mut() {
controller.translation = Some(Vec2::new(1.0, -0.5));
}
}
fn read_result_system(controllers: Query<Entity, &KinematicCharacterControllerOutput>) {
for (entity, output) in controllers.iter() {
println!("Entity {:?} moved by {:?} and touches the ground: {:?}",
entity, output.effective_translation, output.grounded);
}
}
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

/* Configure the character controller when the collider is created. */
commands.spawn()
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController {
// The character offset is set to 0.01.
offset: CharacterLength::Absolute(0.01),
..default()
});
commands.spawn()
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController {
// The character offset is set to 0.01 multiplied by the collider’s height.
offset: CharacterLength::Absolute(0.01),
..default()
});
warning

Is 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

/* Character controller with the positive X axis as the up vector. */
commands.spawn()
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController {
up: Vec2::X,
..default()
});
/* Modify the character controller’s up vector inside of a system. */
fn modify_character_controller_autostep(mut character_controller: Query<&mut KinematicCharacterController>) {
for mut character_controller in character_controllers.iter_mut() {
character_controller.up = Vec2::X;
}
}

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.

/* Configure the character controller when the collider is created. */
// Snap to the ground if the vertical distance to the ground is smaller than 0.5.
commands.spawn()
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController {
// Don’t allow climbing slopes larger than 45 degrees.
max_slope_climb_angle: 45.0.to_radians(),
// Automatically slide down on slopes smaller than 30 degrees.
min_slope_slide_angle: 30.0.to_radians(),
..default()
});
/* Configure snap-to-ground inside of a system. */
fn modify_character_controller_slopes(mut character_controller: Query<&mut KinematicCharacterController>) {
for mut character_controller in character_controllers.iter_mut() {
// Don’t allow climbing slopes larger than 45 degrees.
character_controller.max_slope_climb_angle = 45.0.to_radians();
// Automatically slide down on slopes smaller than 30 degrees.
character_controller.min_slope_slide_angle = 30.0.to_radians();
}
}

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.

/* Configure the character controller when the collider is created. */
// Autostep if the step height is smaller than 0.5, and its width larger than 0.2.
commands.spawn()
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController {
autostep: Some(CharacterAutostep {
max_height: CharacterLength::Absolute(0.5),
min_width: CharacterLength::Absolute(0.2),
include_dynamic_bodies: true,
}),
..default()
});
// Autostep if the step height is smaller than 0.5 multiplied by the character’s height,
// and its width larger than 0.5 multiplied by the character’s width (i.e. half the character’s
// width).
commands.spawn()
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController {
autostep: Some(CharacterAutostep {
max_height: CharacterLength::Relative(0.3),
min_width: CharacterLength::Relative(0.5),
include_dynamic_bodies: true,
}),
..default()
});
/* Configure autostep inside of a system. */
fn modify_character_controller_autostep(mut character_controller: Query<&mut KinematicCharacterController>) {
for mut character_controller in character_controllers.iter_mut() {
character_controller.autostep = Some(CharacterAutostep {
max_height: CharacterLength::Absolute(0.5),
min_width: CharacterLength::Absolute(0.2),
include_dynamic_bodies: true,
});
}
}

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 no up component (i.e. the character isn’t jumping).
  • 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

/* Configure the character controller when the collider is created. */
// Snap to the ground if the vertical distance to the ground is smaller than 0.5.
commands.spawn()
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController {
snap_to_ground: Some(CharacterLength::Absolute(0.5)),
..default()
});
// Snap to the ground if the vertical distance to the ground is smaller than 0.2 times the character’s height
commands.spawn()
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController {
snap_to_ground: Some(CharacterLength::Relative(0.2)),
..default()
});
/* Configure snap-to-ground inside of a system. */
fn modify_character_controller_snap_to_ground(mut character_controller: Query<&mut KinematicCharacterController>) {
for mut character_controller in character_controllers.iter_mut() {
character_controller.snap_to_ground = Some(CharacterLength::Absolute(0.5));
}
}

Filtering#

It is possible to let the character controller ignore some obstacles. This is achieved by configuring the KinematicCharacterController::filter_flags to exclude whole families of obstacles (e.g. all the colliders attached to dynamic rigid-bodies), and KinematicCharacterController::filter_groups to filter based on the colliders collision groups.

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.

/* Read the character controller collisions stored in the character controller’s output. */
fn modify_character_controller_slopes(mut character_controller_outputs: Query<&mut KinematicCharacterControllerOutput>) {
for mut output in outputs.iter_mut() {
for collision in &output.collisions {
// 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 there rigid-bodies. The character controller can apply these forces for you if needed:

/* Configure the character controller when the collider is created. */
commands.spawn()
.insert(Collider::ball(0.5))
.insert(KinematicCharacterController {
// Enable the automatic application of impulses to the dynamic bodies
// hit by the character along its path.
apply_impulse_to_dynamic_bodies: true,
..default()
});
/* Configure dynamic impulses inside of a system. */
fn modify_character_controller_impulses(mut character_controller: Query<&mut KinematicCharacterController>) {
for mut character_controller in character_controllers.iter_mut() {
// Enable the automatic application of impulses to the dynamic bodies
// hit by the character along its path.
character_controller.apply_impulse_to_dynamic_bodies = 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.