首页 > 解决方案 > 旋转到方向向量

问题描述

好的,所以我得到了一个 Three.js 对象。我可以读取对象的旋转,但我想要一个指向对象旋转方向的 vec3,我如何得到它?

标签: javascriptthree.js3d

解决方案


THREEJS 使用四元数而不是以某种顺序围绕 X、Y、Z 旋转。您可以提取四元数轴:

export function deconstructQuaternion(q: THREE.Quaternion) {    
if (q.w > 1) {
    q.normalize(); // if w > 1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
}

const angle = 2 * Math.acos(q.w);
const s = Math.sqrt(1 - q.w * q.w); // assuming quaternion normalized then w is less than 1, so term always positive.
const axis = new THREE.Vector3();
if (s < 0.001) { // test to avoid divide by zero, s is always positive due to sqrt
    // if s close to zero then direction of axis not important
    axis.set(q.x, q.y, q.z); // if it is important that axis is normalized then replace with x=1; y=z=0;
} else {
    // normalize axis
    axis.set(q.x / s, q.y / s, q.z / s)
}

return {
    axis,
    angle
};
}

推荐阅读