问题
I have a body in cannon.js that has a quaternion rotation applied to it. I want to move it 100 units along a vector relative to it's local rotation.
Eg
let body = new CANNON.Body({ mass: 0 });
body.quaternion.setFromAxisAngle(new CANNON.Vec3(0,0,1),(2*Math.PI)/6);
body.position.set(0,0,100); //this is wrong
Using body.position.set(x, y, z);
moves the body relative to the world rather than the local rotation. I think I need to add a vector after applying the quaternion to it, but the docs for cannon.js aren't particularly helpful so I've not been able to work out how to do it.
回答1:
Use the Quaternion#vmult method to rotate a vector and Vec3#add to add the result to the position.
let body = new CANNON.Body({ mass: 0 });
body.quaternion.setFromAxisAngle(new CANNON.Vec3(0,0,1),(2*Math.PI)/6);
let relativeVector = new CANNON.Vec3(0,0,100);
// Use quaternion to rotate the relative vector, store result in same vector
body.quaternion.vmult(relativeVector, relativeVector);
// Add position and relative vector, store in body.position
body.position.vadd(relativeVector, body.position);
来源:https://stackoverflow.com/questions/46810707/position-a-body-in-cannon-js-relative-to-local-rotation