How to Simulate Air Resistance in Ammo.js

Simulating realistic environmental forces like air resistance is crucial for accurate physics simulations. This article provides a straightforward guide on how to adjust the linear damping property of rigid bodies in ammo.js to mimic drag, explaining the APIs involved and providing practical code examples to get it working in your project.

In ammo.js (the Emscripten port of the Bullet physics engine), air resistance is simulated using damping. Damping artificially reduces the velocity of a rigid body over time. To simulate linear air resistance (drag on translational movement), you must adjust the linear damping property of a btRigidBody.

The setDamping Method

To apply damping in ammo.js, use the setDamping method on an active rigid body instance. This method accepts two parameters:

  1. Linear Damping: Controls resistance to movement (translational drag).
  2. Angular Damping: Controls resistance to rotation (rotational drag).
// Syntax
rigidBody.setDamping(linearDamping, angularDamping);

Step-by-Step Implementation

Here is how to apply linear damping to a rigid body in your JavaScript code:

// 1. Create your rigid body construction info as usual
const mass = 1.0;
const localInertia = new Ammo.btVector3(0, 0, 0);
geometry.calculateLocalInertia(mass, localInertia);

const motionState = new Ammo.btDefaultMotionState(transform);
const rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, geometry, localInertia);
const body = new Ammo.btRigidBody(rbInfo);

// 2. Define damping values
// 0.0 represents no air resistance (vacuum)
// 1.0 represents maximum resistance (the body will barely move)
const linearDamping = 0.1;   // Simulated air resistance
const angularDamping = 0.05;  // Simulated rotational air resistance

// 3. Apply the damping to the rigid body
body.setDamping(linearDamping, angularDamping);

// 4. Add the body to the physics world
physicsWorld.addRigidBody(body);

Choosing the Right Values

Terminal Velocity

When you apply linear damping, an object falling under gravity will naturally reach a terminal velocity where the force of gravity is balanced by the damping force. If your object is falling too fast, increase the linearDamping value rather than manually capping the velocity in your render loop.