How to Teleport an Ammo.js Rigid Body
This article explains how to instantly teleport a rigid body to a new coordinate position using the ammo.js physics library. You will learn the exact sequence of API calls required to update the body’s position, clear its existing momentum, and force the physics engine to register the change immediately.
To teleport a rigid body in ammo.js, you cannot simply update its position coordinates. You must update its world transform, sync its motion state, clear any existing velocities, and reactivate the body within the physics simulation.
Here is the step-by-step code implementation to achieve an instant teleportation:
function teleportRigidBody(rigidBody, x, y, z) {
// 1. Create a transform object and set it to the new coordinates
const transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin(new Ammo.btVector3(x, y, z));
// 2. Apply the transform to the body and its motion state
rigidBody.setWorldTransform(transform);
if (rigidBody.getMotionState()) {
rigidBody.getMotionState().setWorldTransform(transform);
}
// 3. Clear existing linear and angular velocities to prevent drifting
const zeroVelocity = new Ammo.btVector3(0, 0, 0);
rigidBody.setLinearVelocity(zeroVelocity);
rigidBody.setAngularVelocity(zeroVelocity);
// 4. Force the physics engine to reactivate the body
rigidBody.activate();
// 5. Clean up allocated Ammo memory
Ammo.destroy(transform);
Ammo.destroy(zeroVelocity);
}Why These Steps Are Necessary
- The Transform Update: Ammo.js relies on transforms
(
btTransform) to track the position and rotation of objects. Updating both the body’s world transform and its motion state ensures that both the physics engine and your 3D renderer (like Three.js) stay in perfect sync. - Velocity Reset: When you teleport an object, it retains its momentum. If the object was falling or moving fast before the teleport, it will continue moving with that same velocity at the new location. Setting the linear and angular velocities to zero prevents this.
- Activation: Physics engines put resting objects to
“sleep” to save CPU cycles. Calling
activate()wakes the body up, forcing the engine to recalculate its collisions at the new coordinates immediately.