character_controller_setup
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:
- Given a desired translation, compute the actual translation that we can apply to the collider based on the obstacles.
- 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.
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.
The built-in character controller does not support rotational movement. It only supports translations.