通过方向计算四元数旋转

 1         // 已知方向,求物体的旋转
 2         public static Quaternion GetRotation(Vector3 knownDirection)
 3         {
 4             knownDirection.Normalize();
 5             // Unity中的世界坐标系中,正前方通常为Vector3.forward (0, 0, 1)
 6             Vector3 forward = Vector3.forward;
 7 
 8             // 计算旋转轴(叉乘结果)和旋转角度(通过点乘)
 9             Vector3 rotationAxis = Vector3.Cross(forward, knownDirection).normalized;
10             float angle = Mathf.Acos(Vector3.Dot(forward, knownDirection) / (forward.magnitude * knownDirection.magnitude));
11 
12             // 将轴角转换为四元数
13             Quaternion rotation = Quaternion.AngleAxis(angle * Mathf.Rad2Deg, rotationAxis);
14 
15             // 输出四元数
16             //Debug.Log("Calculated Quaternion Rotation: " + rotation);
17 
18             return rotation;
19         }

 

posted @ 2024-09-12 17:17  zerozabuu  阅读(6)  评论(0编辑  收藏  举报