如何使旋转最短路径

时间:2019-08-25 10:03:45

标签: c# unity3d rotation

我有一个水箱,由顶部和底部的炮塔组成,两者分开但位于父对象下方。射击时,炮塔将朝射击方向旋转,然后朝坦克的基础旋转回去。 我想以尽可能短的方向旋转炮塔。因此,如果基数为0度,而刀架为270,我将270更改为-90,并且将从-90变为lerp,但是如果基数为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);
    }

这是我当前的代码。当物体朝向0时,它可以正常工作,但是当物体切换为180时,它全部反转。

1 个答案:

答案 0 :(得分:2)

您可以使用Quaternion.Lerp甚至更好的Quaternion.Slerp插值旋转。

Quaternion from = this.transform.rotation;
Quaternion to = playerBody.transform.rotation;

void Update()
{
    transform.rotation = Quaternion.Slerp(from, to, lerpRate);
}
相关问题