Position a body in cannon.js relative to local rotation

余生颓废 提交于 2019-12-11 16:53:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!