Multiply a Vector by a Scalar in Ammo.js
This article explains how to correctly multiply a 3D vector by a numeric scalar in the ammo.js physics library. You will learn the correct syntax using both the built-in Emscripten operator binding and an alternative in-place multiplication method designed to prevent memory leaks in JavaScript.
Using the op_mul
Method
In ammo.js (which is a direct Port of the Bullet physics engine via
Emscripten), standard C++ mathematical operators are exposed as methods.
The multiplication operator (*) for a
btVector3 and a float scalar is bound to the
op_mul method.
// Create a vector and define a scalar
const vector = new Ammo.btVector3(1.0, 2.0, 3.0);
const scalar = 2.5;
// Multiply the vector by the scalar
const scaledVector = vector.op_mul(scalar);
console.log(scaledVector.x(), scaledVector.y(), scaledVector.z()); // Outputs: 2.5, 5.0, 7.5Memory Management Caution
Because op_mul returns a brand new
btVector3 instance allocated on the WebAssembly heap, you
must manually destroy the resulting vector when you are done using it to
avoid memory leaks.
// Clean up the allocated vectors
Ammo.destroy(vector);
Ammo.destroy(scaledVector);The In-Place Multiplication Alternative (Recommended)
To avoid garbage collection overhead and potential memory leaks
caused by creating new objects in high-frequency loops (such as your
game’s update loop), you can modify the original vector’s components in
place using setValue().
const vector = new Ammo.btVector3(1.0, 2.0, 3.0);
const scalar = 2.5;
// Multiply in-place without allocating new memory
vector.setValue(
vector.x() * scalar,
vector.y() * scalar,
vector.z() * scalar
);
console.log(vector.x(), vector.y(), vector.z()); // Outputs: 2.5, 5.0, 7.5
// Only destroy the original vector when it is no longer needed
Ammo.destroy(vector);Using the in-place method is the best practice for performance-critical WebGL applications, as it completely bypasses the creation of temporary WebAssembly objects.