统一旋转差异和方向

时间:2015-04-28 09:56:20

标签: c# unity3d rotation

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

我尝试使用Quaternion.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),这将返回Y角度差异为0.8而不是3

2 个答案:

答案 0 :(得分:1)

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

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对此进行测试。

答案 1 :(得分:0)

方向使用:

Vector3 offset =  transform.position - target.position;
相关问题