Create a Static Rigid Body in Ammo.js
Creating a perfectly static rigid body in ammo.js—the JavaScript port of the Bullet physics engine—is essential for building immovable environment colliders like floors, walls, and obstacles. This guide provides a direct, step-by-step walkthrough on how to configure your rigid body with zero mass, set up its motion state, and instantiate it properly so that it remains completely unaffected by gravity, forces, and physical collisions.
1. Set the Mass to Zero
In Bullet and ammo.js, the mass of a rigid body determines its
physical behavior. Setting the mass to exactly 0 tells the
physics engine that the body is static. Static bodies have infinite
mass, meaning they will not move under the influence of gravity,
collisions, or any applied forces.
2. Set Local Inertia to Zero
Because a static body does not move or rotate, its local inertia must
also be zero. You do not need to calculate inertia using the collision
shape’s calculateLocalInertia method; instead, pass a
zeroed vector.
var mass = 0;
var localInertia = new Ammo.btVector3(0, 0, 0);3. Create the Motion State and Shape
Define the position and rotation of your static body using a
btTransform. Pass this transform to a
btDefaultMotionState to track the object’s initial
orientation. Next, define your collision geometry, such as a box,
sphere, or static plane.
// Position and rotation
var transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin(new Ammo.btVector3(0, -1, 0)); // Positioned at y = -1
var motionState = new Ammo.btDefaultMotionState(transform);
// Collision shape (e.g., a ground plane box)
var boxShape = new Ammo.btBoxShape(new Ammo.btVector3(50, 1, 50)); // half-extents4. Instantiate the Rigid Body
Combine the mass, motion state, shape, and inertia into a
btRigidBodyConstructionInfo object, then instantiate the
rigid body and add it to your physics world.
// Construction info
var rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, motionState, boxShape, localInertia);
var body = new Ammo.btRigidBody(rbInfo);
// Add the body to your pre-existing physics world
physicsWorld.addRigidBody(body);5. Collision Flags (Optional)
While setting the mass to 0 automatically configures the
body as static, you can explicitly set the collision flags to guarantee
the engine treats it as a static object. This can optimize collision
detection.
body.setCollisionFlags(body.getCollisionFlags() | 1); // 1 is the CF_STATIC_OBJECT flag