Set Max Slope Angle in Ammo.js Character Controller
This article explains how to configure the maximum slope angle a
character can climb when using the
btKinematicCharacterController in the ammo.js physics
engine. You will learn the specific API method required, how to convert
your target angle into the correct unit, and how to implement this in
your JavaScript code.
To set the maximum slope angle that a
btKinematicCharacterController can walk up, you must use
the setMaxSlope method. This method defines the limit of
the incline angle; any slope steeper than this limit will prevent the
character controller from climbing and cause it to slide down or
stop.
The setMaxSlope Method
The setMaxSlope method accepts a single argument of type
btScalar (a float), representing the angle in
radians.
characterController.setMaxSlope(slopeRadians);Step-by-Step Implementation
Because the method requires radians, you will typically need to convert your desired angle from degrees to radians before passing it to the controller.
1. Convert Degrees to Radians
To convert degrees to radians, use the standard mathematical formula: \[\text{Radians} = \text{Degrees} \times \frac{\pi}{180}\]
In JavaScript, this is written as:
const maxSlopeDegrees = 45.0; // Desired maximum climb angle
const maxSlopeRadians = maxSlopeDegrees * (Math.PI / 180);2. Apply to the Controller
Pass the calculated radian value to your instance of
btKinematicCharacterController:
// Assuming 'characterController' is your active Ammo.btKinematicCharacterController instance
characterController.setMaxSlope(maxSlopeRadians);Complete Code Example
Here is how the configuration looks within a typical ammo.js initialization setup:
// 1. Create the ghost object and shape for the character
const ghostObject = new Ammo.btPairCachingGhostObject();
const sphereShape = new Ammo.btSphereShape(0.5);
// 2. Instantiate the kinematic character controller
const stepHeight = 0.35;
const characterController = new Ammo.btKinematicCharacterController(
ghostObject,
sphereShape,
stepHeight
);
// 3. Set the maximum slope angle to 45 degrees
const maxSlopeAngleInDegrees = 45;
const maxSlopeAngleInRadians = maxSlopeAngleInDegrees * (Math.PI / 180);
characterController.setMaxSlope(maxSlopeAngleInRadians);
// 4. (Optional) Verify the setting using the getter method
const currentMaxSlope = characterController.getMaxSlope();
console.log("Max slope in radians: " + currentMaxSlope);Expected Behavior
- Slopes under the limit: The character controller will step up the incline smoothly.
- Slopes over the limit: The character will treat the slope as a wall or obstacle, preventing upward movement.