While working with Cannon.js and following online examples, I encountered an issue where setting certain properties in the constructor resulted in NaN values for the position and angular velocity (x, y, z).
For instance, when initializing a body without setting the mass, it does not move:
const body = new CANNON.Body();
console.log(body.position.x, body.mass); //logs 0, 0
However, when specifying the mass in the constructor, the position values become NaN:
const body = new CANNON.Body({
mass: 1,
});
console.log(body.position.x, body.mass); //logs NaN, 1
Even setting the mass after instantiating the body does not solve the issue.
Here is some additional code context (including the update function called in an animation loop):
export const init = () => {
world = new CANNON.World();
world.gravity.set(0,1,0);
world.broadphase = new CANNON.NaiveBroadphase();
world.solver.iterations = 10;
for (let i = 0; i < BODIES_COUNT; i++) {
const shape = new CANNON.Box(new CANNON.Vec3(4,4,4));
const body = new CANNON.Body({
mass: 1,
});
body.addShape(shape);
body.position.set(0, 0, 0);
body.mass = 1;
body.angularVelocity.set(0, 2, 0);
body.velocity.set(0, 1, 0);
body.angularDamping = 0.5;
world.addBody(body);
bodies.push(body);
const geometry = new THREE.BoxGeometry(10, 10, 10);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
const mesh = new THREE.Mesh(geometry, material);
meshes.push(mesh);
}
}
export const update = (delta) => {
world.step(TIMESTEP * delta);
}