How to Calculate Dot Product in Ammo.js

This article explains how to quickly calculate the dot product of two directional vectors using Ammo.js, the JavaScript port of the Bullet physics engine. You will learn how to define 3D vectors using the library's native classes and utilize the built-in mathematical functions to determine their spatial relationship.

In Ammo.js, 3D vectors are represented by the btVector3 class. To calculate the dot product of two directional vectors, you can use the built-in .dot() method. This method takes another btVector3 as an argument and returns a scalar float value.

Step-by-Step Implementation

First, ensure you have initialized Ammo.js. Then, instantiate your two directional vectors and call the .dot() method:

// 1. Create the two directional vectors (btVector3)
const vectorA = new Ammo.btVector3(1.0, 0.0, 0.0); // Pointing along the X-axis
const vectorB = new Ammo.btVector3(0.707, 0.707, 0.0); // Pointing 45-degrees between X and Y

// 2. Calculate the dot product
const dotProduct = vectorA.dot(vectorB);

console.log(`The dot product is: ${dotProduct}`); // Output: ~0.707

// 3. Clean up WebAssembly memory
Ammo.destroy(vectorA);
Ammo.destroy(vectorB);

Understanding the Result

The resulting scalar value of the dot product tells you the directional relationship between the two normalized vectors:

  • 1.0: The vectors are pointing in the exact same direction.
  • Greater than 0: The vectors point in the same general direction (the angle between them is acute, less than 90 degrees).
  • 0.0: The vectors are perpendicular (at a 90-degree angle).
  • Less than 0: The vectors point in opposite general directions (the angle between them is obtuse, greater than 90 degrees).
  • -1.0: The vectors are pointing in exactly opposite directions.

Memory Management Note

Because Ammo.js is a WebAssembly/C++ wrapper, objects created with the new keyword (like btVector3) allocate memory on the heap. Always use Ammo.destroy(vector) once you are finished with the vectors to prevent memory leaks in your application.