How to Clear Forces on a Rigid Body in Ammo.js
This article explains how to completely stop a rigid body and clear all of its active forces in the ammo.js physics engine. You will learn the exact API methods required to reset accumulated forces, nullify linear and angular velocities, and properly update the physics state to ensure your 3D objects instantly come to a complete halt.
In ammo.js (a JavaScript port of the Bullet physics engine), simply clearing the external forces applied to a rigid body is often not enough to stop it from moving. To properly reset a body to a stationary state, you must clear its accumulated forces, reset its linear and angular velocities to zero, and re-activate the body within the physics world.
Here is the step-by-step process and the code required to achieve this.
Step 1: Clear Accumulated Forces
First, you must clear any forces that were applied to the rigid body
during the current physics step using the clearForces
method.
rigidBody.clearForces();Step 2: Reset Velocities to Zero
While clearing forces stops new accelerations from being applied, the rigid body will keep moving if it already has momentum. To stop all movement and rotation immediately, you must set both the linear and angular velocities to zero.
Because ammo.js uses WebIDL/C++ wrappers, you must pass a
btVector3 object representing zero velocity.
// Create a zero vector
const zeroVector = new Ammo.btVector3(0, 0, 0);
// Reset linear velocity (stops translation)
rigidBody.setLinearVelocity(zeroVector);
// Reset angular velocity (stops rotation)
rigidBody.setAngularVelocity(zeroVector);Step 3: Activate the Rigid Body
If a rigid body remains stationary for a certain period, the physics
engine puts it into a “sleeping” state to save performance. If you clear
forces and velocities on a sleeping body, it may not register future
physics updates correctly. To prevent this, force the body to wake up
using the activate method.
rigidBody.activate();Step 4: Clean Up Memory
To prevent memory leaks in your JavaScript application, always
destroy any temporary btVector3 objects you instantiated
once you are finished using them.
Ammo.destroy(zeroVector);Complete Helper Function
Below is a reusable helper function that safely and cleanly resets all forces and velocities acting on an ammo.js rigid body:
function clearRigidBodyForces(rigidBody) {
const zeroVector = new Ammo.btVector3(0, 0, 0);
rigidBody.clearForces();
rigidBody.setLinearVelocity(zeroVector);
rigidBody.setAngularVelocity(zeroVector);
rigidBody.activate();
Ammo.destroy(zeroVector);
}