Calculate Wheel Position in Ammo.js Vehicle

This article explains how to calculate and retrieve the exact global position and rotation of a spinning wheel in an ammo.js raycast vehicle. By utilizing the built-in vehicle physics engine methods, you can accurately track wheel coordinates and orientation in 3D space for rendering or gameplay mechanics.

In ammo.js, wheels on a btRaycastVehicle are not simulated as individual rigid bodies. Instead, their positions and rotations are calculated dynamically on each physics step using suspension casting, steering angles, and engine rotation (spin). To obtain the exact global position of a wheel, you must query the vehicle’s updated transform data.

Step-by-Step Implementation

To get the exact global position and rotation of a specific wheel, follow these steps:

1. Update the Wheel Transform

Before reading the coordinates, you must instruct the vehicle to update the wheel’s world transform. This ensures that suspension travel, steering, and roll are factored into the final coordinates.

// 'vehicle' is your Ammo.btRaycastVehicle instance
// 'index' is the index of the wheel (e.g., 0 for front-left, 1 for front-right)
const interpolate = true; 
vehicle.updateWheelTransform(index, interpolate);

Setting the second parameter to true enables interpolation, which provides smoother visual positioning between physics steps.

2. Retrieve the World Transform

Once updated, you can access the wheel’s information object and extract its world transform matrix.

const wheelInfo = vehicle.getWheelInfo(index);
const transform = wheelInfo.get_m_worldTransform();

3. Extract Position and Rotation

From the transform, you can extract the exact origin (position vector) and rotation (quaternion).

// Extract Global Position
const origin = transform.getOrigin();
const posX = origin.x();
const posY = origin.y();
const posZ = origin.z();

// Extract Global Rotation
const rotation = transform.getRotation();
const rotX = rotation.x();
const rotY = rotation.y();
const rotZ = rotation.z();
const rotW = rotation.w();

Applying Coordinates to a 3D Mesh (e.g., Three.js)

If you are using a rendering library like Three.js, you can apply these extracted values directly to your wheel mesh on every frame:

function updateWheelMesh(wheelMesh, vehicle, index) {
    // Update transform in physics engine
    vehicle.updateWheelTransform(index, true);
    
    // Get transform data
    const transform = vehicle.getWheelInfo(index).get_m_worldTransform();
    const origin = transform.getOrigin();
    const rotation = transform.getRotation();
    
    // Apply to Three.js Mesh
    wheelMesh.position.set(origin.x(), origin.y(), origin.z());
    wheelMesh.quaternion.set(rotation.x(), rotation.y(), rotation.z(), rotation.w());
}

By calling this update function within your render loop, your visual wheel meshes will perfectly align with the exact physics coordinates of the spinning wheels.