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