Calculate Distance Between Two btVector3 in Ammo.js

This article explains how to accurately calculate the 3D mathematical distance between two btVector3 points in ammo.js, the JavaScript port of the Bullet Physics engine. You will learn the two primary ways to achieve this: using the built-in native Ammo.js methods for simplicity, and using manual coordinate extraction for optimal performance and memory management.

Method 1: Using the Native Ammo.js API

The simplest and most direct way to find the distance between two btVector3 points is by using the native methods wrapped from the C++ Bullet Physics library. The btVector3 class exposes both distance() and distance2() (squared distance) methods.

To get the actual Euclidean distance:

// Assuming point1 and point2 are instantiated Ammo.btVector3 objects
const distance = point1.distance(point2);

If you only need to compare distances (for example, sorting objects by proximity or checking if an object is within a certain radius), it is highly recommended to use the squared distance. This avoids the computationally expensive square root operation:

const distanceSq = point1.distance2(point2);

// Check if distance is less than 5 units
if (distanceSq < 25) { // 25 is 5 squared
    // Points are close
}

Method 2: Manual Calculation (Best for Performance)

Ammo.js runs inside WebAssembly (or asm.js). Frequently calling native WebAssembly methods or creating temporary vectors can introduce performance overhead. For high-frequency calculations (such as inside a physics tick or render loop), extracting the coordinates and calculating the distance using standard JavaScript math is often faster.

You can retrieve the x, y, and z coordinates using the getter functions and apply the 3D distance formula:

\[\text{Distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2 + (z_2 - z_1)^2}\]

Here is how to implement this in JavaScript:

function getDistance(p1, p2) {
    const dx = p1.x() - p2.x();
    const dy = p1.y() - p2.y();
    const dz = p1.z() - p2.z();
    
    return Math.sqrt(dx * dx + dy * dy + dz * dz);
}

// Usage
const distance = getDistance(point1, point2);

Similarly, the performance-optimized squared distance helper:

function getDistanceSq(p1, p2) {
    const dx = p1.x() - p2.x();
    const dy = p1.y() - p2.y();
    const dz = p1.z() - p2.z();
    
    return dx * dx + dy * dy + dz * dz;
}

Summary of Choice

Use Method 1 (point1.distance(point2)) when writing clean, readable code for occasional distance checks. Use Method 2 (Manual math) inside loops, physics update steps, or when managing thousands of active entities to avoid garbage collection spikes and WebAssembly call overhead.