Kevin Castejon
Kevin Castejon

Reputation: 122

Cannonjs move body forward according to its quaternion

I'm struggling with Cannonjs physics lib, I got a sphere body with a changing quaternion, I just want that body to move forward according to its quaternion. I found many topics related to that but none of the suggested codes is working. Is it a simple way to achieve that simple task?

So far I tried the solution given here but the using of vmult() method do not change the vector3 at all...

body.quaternion = new CANNON.Quaternion(0,1,0,0);          // Whatever value you put here will not change the result of the vmult() operation below
var localVelocity = new CANNON.Vec3(0, 0, 1);
var worldVelocity = body.quaternion.vmult(localVelocity);  //-> worldVelocity = (0,0,1)
body.velocity.copy(worldVelocity);

Upvotes: 1

Views: 614

Answers (1)

lortschi
lortschi

Reputation: 4323

Try to set and not copy the body.velocity, this way:

let directionVector = new CANNON.Vec3(0, 0, 1);
directionVector.z -= moveDistance;
directionVector = vehicleBody.quaternion.vmult( directionVector );
vehicleBody.velocity.set( directionVector.x, directionVector.y, directionVector.z );

Upvotes: 1

Related Questions