如何 Lerp 旋转最短路径
How to Lerp a rotation the shortest path
我有一辆坦克,它由底座和顶部的炮塔组成,两者是分开的,但在 parent object 之下。射击时,炮塔将旋转到射击方向,然后向坦克基地旋转方向倾斜。
我想以尽可能短的方向旋转炮塔。因此,如果底座为 0 度且炮塔为 270,我将 270 更改为 -90,它将从 -90 倾斜到 0,但是如果底座为 180 且炮塔为 270,则需要倾斜从 270 到 180,而不是从 -90。
这是我当前的代码。
void StackFunction()
{
float turretRotation;
float bodyRotation;
turretRotation = this.transform.eulerAngles.y;
bodyRotation = playerBody.transform.eulerAngles.y;
if (turretRotation > 180)
{
turretRotation -= 360;
}
float targetRotation = Mathf.Lerp(turretRotation, bodyRotation, lerpRate);
this.gameObject.transform.eulerAngles = new Vector3(this.gameObject.transform.eulerAngles.x, targetRotation, this.gameObject.transform.eulerAngles.z);
}
这是我当前的代码。当 body 面向 0 时它工作正常,但是当 body 交换为 180 时它全部反转。
您可以使用 Quaternion.Lerp or even better Quaternion.Slerp 插入旋转。
Quaternion from = this.transform.rotation;
Quaternion to = playerBody.transform.rotation;
void Update()
{
transform.rotation = Quaternion.Slerp(from, to, lerpRate);
}
我有一辆坦克,它由底座和顶部的炮塔组成,两者是分开的,但在 parent object 之下。射击时,炮塔将旋转到射击方向,然后向坦克基地旋转方向倾斜。 我想以尽可能短的方向旋转炮塔。因此,如果底座为 0 度且炮塔为 270,我将 270 更改为 -90,它将从 -90 倾斜到 0,但是如果底座为 180 且炮塔为 270,则需要倾斜从 270 到 180,而不是从 -90。
这是我当前的代码。
void StackFunction()
{
float turretRotation;
float bodyRotation;
turretRotation = this.transform.eulerAngles.y;
bodyRotation = playerBody.transform.eulerAngles.y;
if (turretRotation > 180)
{
turretRotation -= 360;
}
float targetRotation = Mathf.Lerp(turretRotation, bodyRotation, lerpRate);
this.gameObject.transform.eulerAngles = new Vector3(this.gameObject.transform.eulerAngles.x, targetRotation, this.gameObject.transform.eulerAngles.z);
}
这是我当前的代码。当 body 面向 0 时它工作正常,但是当 body 交换为 180 时它全部反转。
您可以使用 Quaternion.Lerp or even better Quaternion.Slerp 插入旋转。
Quaternion from = this.transform.rotation;
Quaternion to = playerBody.transform.rotation;
void Update()
{
transform.rotation = Quaternion.Slerp(from, to, lerpRate);
}