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:
- Linear Damping: Controls resistance to movement (translational drag).
- 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
- Default Value: By default, Bullet/ammo.js
initializes rigid bodies with a damping value of
0.0(no drag). - Low Drag (e.g., 0.01 to 0.1): Ideal for sleek, heavy objects moving through air, like a baseball or a drop of water.
- Medium Drag (e.g., 0.2 to 0.5): Ideal for lightweight objects with high surface area, like a falling leaf or a feather.
- High Drag (e.g., > 0.8): Useful for simulating movement through thick fluids like water or oil.
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.