Jack Wild
Jack Wild

Reputation: 2122

Cannon JS — Position Vector NaN after initiating body with properties

I'm using a simple setup Cannon.js, following the examples online, but when I set any property in the constructor, the position and angular velocity x, y and z are all NaN.

This works, but does not move, as the body has no mass.

const body = new CANNON.Body();
console.log(body.position.x, body.mass); //logs 0, 0

However, this doesn't...

const body = new CANNON.Body({
    mass: 1,
});
console.log(body.position.x, body.mass); //logs NaN, 1

Also if I instantiate the body, and then set the mass after, it still doesn't move.

Some more code for context (I am calling the update function in an animation loop, and it's happening A-OK).

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,
    });
    const body = new CANNON.Body();
    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);
}

Upvotes: 3

Views: 1067

Answers (1)

schteppe
schteppe

Reputation: 2084

The only thing I can think of is that you accidentally pass delta = 0 to world.step. Repro using Cannon.js v0.6.2: JSFiddle

Try changing your code to:

export const update = (delta) => {
    if (delta > 0) {
        world.step(TIMESTEP * delta);
    }
}

Upvotes: 5

Related Questions