Configure Ammo.js Linear and Angular Sleep Thresholds
This article explains how to configure the linear and angular sleep thresholds for rigid bodies in an ammo.js physics simulation. By adjusting these thresholds, you can control when inactive physics bodies enter a sleeping state, significantly reducing CPU usage and improving the overall performance of your 3D application.
In ammo.js (a direct JavaScript port of the Bullet Physics engine), sleep parameters are configured on individual rigid bodies rather than globally on the physics world. When a body’s linear velocity and angular velocity fall below their respective thresholds for a specific amount of time, the physics engine disables its simulation updates until an external force acts upon it again.
Step 1: Access the Rigid Body
To configure sleep thresholds, you must target an instance of
Ammo.btRigidBody.
// Example of creating a rigid body
const transform = new Ammo.btTransform();
transform.setIdentity();
const motionState = new Ammo.btDefaultMotionState(transform);
const localInertia = new Ammo.btVector3(0, 0, 0);
const shape = new Ammo.btBoxShape(new Ammo.btVector3(1, 1, 1));
shape.calculateLocalInertia(1.0, localInertia);
const constructionInfo = new Ammo.btRigidBodyConstructionInfo(
1.0, // Mass
motionState,
shape,
localInertia
);
const rigidBody = new Ammo.btRigidBody(constructionInfo);Step 2: Set the Sleep Thresholds
Use the setSleepingThresholds method on the rigid body
instance. This method accepts two arguments: the linear velocity
threshold and the angular velocity threshold.
const linearThreshold = 0.8; // Velocity in meters per second
const angularThreshold = 1.0; // Angular velocity in radians per second
rigidBody.setSleepingThresholds(linearThreshold, angularThreshold);- Linear Threshold: The minimum linear velocity required to keep the body active. If the body moves slower than this value, it becomes a candidate for sleeping.
- Angular Threshold: The minimum angular velocity (rotation speed) required to keep the body active.
Step 3: Configure Deactivation Time (Optional)
A body does not sleep instantly when its velocity falls below the
threshold; it must remain below the threshold for a designated period.
You can configure this time using setDeactivationTime.
const deactivationTime = 2.0; // Time in seconds
rigidBody.setDeactivationTime(deactivationTime);Step 4: Ensure Deactivation is Enabled
By default, rigid bodies are allowed to sleep. However, if you have previously disabled deactivation, you must re-enable it by setting the activation state.
// 1 = ACTIVE_TAG, 2 = ISLAND_SLEEPING, 4 = DISABLE_DEACTIVATION
rigidBody.setActivationState(1); Do not set the activation state to 4
(DISABLE_DEACTIVATION), as this prevents the rigid body
from ever entering the sleeping state, rendering your threshold
configurations useless.