向目标对象平滑旋转对象

Sid*_*rth 5 c# unity-game-engine

我想将我的玩家车辆旋转到目标对象的方向/侧面。虽然是下图,但我试图以更好的方式解释我的观点:

在此处输入图片说明

我想将下面的坦克对象旋转到另一个坦克对象,以便它可以指向那个方向。

我为此目的编写了此代码,但它不起作用:

IEnumerator DoRotationAtTargetDirection(Transform opponentPlayer)
{
    Quaternion targetRotation = Quaternion.identity;
    do
    {
        Debug.Log("do rotation");
        Vector3 targetDirection = opponentPlayer.position - transform.position;
        targetRotation = Quaternion.LookRotation(targetDirection);
        Quaternion nextRotation = Quaternion.Lerp(transform.localRotation, targetRotation, Time.deltaTime);
        transform.localRotation = nextRotation;
        yield return null;

    } while (Quaternion.Angle(transform.localRotation, targetRotation) < 0.01f);
}
Run Code Online (Sandbox Code Playgroud)

我只想平稳地旋转并停止朝向目标对象。请分享您对此的建议。

编辑:

这是仍然无法正常工作的更新代码,坦克对象像上图一样卡在旋转中:

 IEnumerator DoRotationAtTargetDirection(Transform opponentPlayer)
{
    Quaternion targetRotation = Quaternion.identity;
    do
    {
        Debug.Log("do rotation");

        Vector3 targetDirection = (opponentPlayer.position - transform.position).normalized;
        targetRotation = Quaternion.LookRotation(targetDirection);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, Time.deltaTime);

        yield return null;

    } while (Quaternion.Angle(transform.rotation, targetRotation) < 0.01f);
}
Run Code Online (Sandbox Code Playgroud)

坦克对象前进方向:

在此处输入图片说明

Ruz*_*ihm 2

Time.deltaTime是一个不合适的 lerp 参数。相反,定义 afloat rotationSpeed并用作的rotationSpeed * Time.deltaTime参数。maxDegreesDeltaQuaternion.RotateTowards

另外,LookRotation以这种方式使用会给你一个世界空间旋转。所以你应该将你的结果分配给transform.rotation而不是transform.localRotation.

总而言之,这些更改可能如下所示:

public float rotationSpeed;

IEnumerator DoRotationAtTargetDirection(Transform opponentPlayer)
{
    Quaternion targetRotation = Quaternion.identity;
    do
    {
        Debug.Log("do rotation");
        Vector3 targetDirection = opponentPlayer.position - transform.position;
        targetRotation = Quaternion.LookRotation(targetDirection);
        Quaternion nextRotation = Quaternion.RotateTowards(
                transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);
        transform.rotation = nextRotation;
        yield return null;

    } while (Quaternion.Angle(transform.rotation, targetRotation) > 0.01f);
}
Run Code Online (Sandbox Code Playgroud)

  • 1. RotateTowards 永远不会超出目标。如果您将“Lerp”与“Time.deltaTime”一起使用,并且设备由于某种原因而滞后,因此您的帧具有非常大的“Time.deltaTime &gt; 1”,那么它将输出一个可能旋转超出其范围的结果应该去。如果“Time.deltaTime &gt; 2”,那么它会比之前距离目标更远。理论上你可以使用 `Lerp(a,b,Mathf.Min(1f,Time.deltaTime))`; (2认同)