Force Ammo.js Rigid Body to Sleep State
This article explains how to explicitly force an active rigid body in Ammo.js to enter a sleep (deactivated) state. By putting idle physics bodies to sleep, you can significantly optimize your application’s simulation performance and reduce CPU overhead.
To force a rigid body to sleep in Ammo.js, you must set its
activation state to ISLAND_SLEEPING (which corresponds to
the integer value 2) and reset its velocities to prevent
the physics engine from immediately waking it up in the next frame.
Step-by-Step Implementation
1. Zero Out Velocities and Forces
Before forcing the sleep state, you must clear any remaining motion and forces acting on the rigid body. If the body is still moving or has active forces applied, the physics engine will instantly wake it back up.
// Create a zero vector
const zeroVector = new Ammo.btVector3(0, 0, 0);
// Clear linear and angular velocities
rigidBody.setLinearVelocity(zeroVector);
rigidBody.setAngularVelocity(zeroVector);
// Clear any applied forces and torques
rigidBody.clearForces();2. Force the Sleep Activation State
In Bullet Physics (and consequently Ammo.js), rigid body activation
states are represented by integers. The state for deactivated/sleeping
bodies is ISLAND_SLEEPING, which has a constant value of
2.
Use the forceActivationState method to apply this
state:
const ISLAND_SLEEPING = 2;
rigidBody.forceActivationState(ISLAND_SLEEPING);Complete Code Helper Function
Below is a reusable JavaScript function to cleanly force any Ammo.js rigid body into a sleep state:
function putRigidBodyToSleep(rigidBody) {
if (!rigidBody) return;
// 1. Stop all movement
const zeroVector = new Ammo.btVector3(0, 0, 0);
rigidBody.setLinearVelocity(zeroVector);
rigidBody.setAngularVelocity(zeroVector);
rigidBody.clearForces();
// 2. Force the sleeping state (ISLAND_SLEEPING = 2)
rigidBody.forceActivationState(2);
// Clean up temporary Ammo object to prevent memory leaks
Ammo.destroy(zeroVector);
}By calling this function, the physics engine will stop simulating the
body’s movement until another active physical object collides with it or
you manually reactivate it using rigidBody.activate().