gpt4 book ai didi

c# - unity 旋转差和方向

转载 作者:太空宇宙 更新时间:2023-11-03 13:08:40 28 4
gpt4 key购买 nike

我想知道两个物体在一个轴上的旋转差异,例如在 Y 轴上。

我尝试使用 Quaternion.Angle 但它计算的是整个旋转,而不是在一个轴上

使用

angle=transform.rotation.eulerAngles.y-target.transform.rotation.eulerAngles.y;

作品,然而,这并没有告诉我目标相对于我的方向,向左或向右有多少角度?

编辑:不,它不起作用,它仅在变换的 x 和 z 旋转轴均为 0 时才起作用。

例如,如果我把两个开始旋转都放在 (349.8176,113.8314,254.5617),然后我将目标向右旋转 3 度,它变成了 (352.7103,113.0266,254.684),这将返回 0.8 的 Y 角度差而不是 3

最佳答案

您可以简单地使用前向向量之间的标量积来确定它们是面向同一方向还是相互注视(或远离):

float dot = Vector3.Dot( transform.forward, target.transform.forward );
bool sameDirection = dot >= 0;

您甚至可以使用矢量数学来计算角度,而无需展开巨大的四元数设定:

// align forward vectors to the XZ plane / Y axis first
Vector3 sourceForward = transform.forward;
Vector3.OrthoNormalize( Vector3.up, ref sourceForward );
Vector3 targetForward = target.transform.forward;
Vector3.OrthoNormalize( Vector3.up, ref targetForward );

// get the angle between both transforms arount the Y axis
float dot = Vector3.Dot( sourceForward, targetForward );
float angleRad = Mathf.Acos( dot );
float angleDeg = Mathf.Rad2Deg( angleRad );

// see if the angle is clockwise or counter-clockwise
Vector3 up = Vector3.Cross( sourceForward, targetForward );
angleDeg = up.y < 0 ? -angleDeg : +angleDeg;

免责声明:这一切都是纯理论的,因为我目前无法使用 Unity 3D 对其进行测试。

关于c# - unity 旋转差和方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29916137/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com