How to Get Basis Vectors from Ammo.js btMatrix3x3

This article explains how to extract the three basis vectors—representing the local X, Y, and Z directional axes—from a btMatrix3x3 rotation matrix in Ammo.js. You will learn the specific API methods required to access these vectors and how to properly manage WebAssembly memory during the extraction process.

In Ammo.js (the JavaScript port of the Bullet Physics engine), a btMatrix3x3 stores three orthogonal unit vectors that define the orientation of a 3D object. These are known as the basis vectors:

Step-by-Step Extraction

To extract these vectors, use the getRow() method of the btMatrix3x3 instance. This method takes an index (0, 1, or 2) as an argument and returns a btVector3 object.

Here is the direct code implementation:

// Assuming 'matrix' is an existing Ammo.btMatrix3x3 instance

// 1. Extract the basis vectors
const basisX = matrix.getRow(0); // Local X-axis (Right)
const basisY = matrix.getRow(1); // Local Y-axis (Up)
const basisZ = matrix.getRow(2); // Local Z-axis (Forward)

// 2. Access the individual vector coordinates
console.log(`X-axis: x=${basisX.x()}, y=${basisX.y()}, z=${basisX.z()}`);
console.log(`Y-axis: x=${basisY.x()}, y=${basisY.y()}, z=${basisY.z()}`);
console.log(`Z-axis: x=${basisZ.x()}, y=${basisZ.y()}, z=${basisZ.z()}`);

Memory Management in Ammo.js

Because Ammo.js is compiled from C++ via Emscripten, calling getRow() allocates new C++ objects on the heap. To prevent memory leaks, you must manually destroy the retrieved btVector3 objects once you are finished using them.

// Perform operations with the vectors
const directionX = new THREE.Vector3(basisX.x(), basisX.y(), basisX.z());

// Free the WebAssembly memory
Ammo.destroy(basisX);
Ammo.destroy(basisY);
Ammo.destroy(basisZ);