You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Three.js实现球体两点间旋转定位(类似Unity的FromToRotation)

在Three.js中实现类似Unity Quaternion.FromToRotation的功能

要让球体上的一个点旋转到目标位置,你可以使用Three.js中THREE.Quaternion的setFromUnitVectors方法,它和Unity的Quaternion.FromToRotation功能完全等效,用于计算从一个单位向量到另一个单位向量的旋转四元数。

实现步骤

  • 计算方向向量:分别获取原始点和目标点相对于球心的方向向量(球体旋转绕自身中心进行)。
  • 归一化向量:将两个方向向量转换为单位向量(setFromUnitVectors要求输入为单位向量)。
  • 生成旋转四元数:使用setFromUnitVectors生成旋转四元数。
  • 应用旋转到球体:将四元数赋值给球体的quaternion属性。

代码示例

// 假设已创建球体对象sphere,以及世界坐标下的原始点pointA、目标点pointB
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);

// 计算相对于球心的方向向量
const startDirection = pointA.clone().sub(sphere.position).normalize();
const targetDirection = pointB.clone().sub(sphere.position).normalize();

// 创建并设置旋转四元数
const rotationQuaternion = new THREE.Quaternion();
rotationQuaternion.setFromUnitVectors(startDirection, targetDirection);

// 将旋转应用到球体
sphere.quaternion.copy(rotationQuaternion);

// 若需叠加现有旋转,可使用multiply:
// sphere.quaternion.multiply(rotationQuaternion);

注意事项

如果两个方向向量完全反向(点积接近-1),setFromUnitVectors无法直接计算,此时可绕任意垂直于该向量的轴旋转180度,示例代码:

const axis = new THREE.Vector3(1, 0, 0);
if (startDirection.dot(targetDirection) < -0.999999) {
    rotationQuaternion.setFromAxisAngle(axis, Math.PI);
}

内容的提问来源于stack exchange,提问作者RevRedBeard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 03:23:32