Unity Lerp和Slerp运动不顺畅

时间:2016-03-07 13:35:01

标签: c# unity3d interpolation

我创建了一个Coroutine来处理我的相机移动和方向,以及在我的协程中:

public IEnumerator MoveCameraLookAtObject(Transform _cameraTransform, Vector3 startPos, Vector3 endPos, Vector3 lookAt, float time)
{
    // Loop through a timed based situation.
    for (float i = 0f; i <= 1.0f; i += Time.deltaTime / time)
    {
        // Lerp the Movement.
        _cameraTransform.position = Vector3.Lerp(startPos, endPos, i);
        // Slerp the rotation.
        Vector3 relativePos = lookAt - _cameraTransform.position;
        Quaternion rotation = Quaternion.LookRotation(relativePos);
        _cameraTransform.rotation = Quaternion.Slerp(_cameraTransform.rotation, rotation, i);
        }
        yield return null;
    }
}

问题在于,当我实际上是Lerping和Slerping时,它看起来很糟糕而且不顺利。我很困惑我做错了什么,因为我花了好几天试图解决这个问题。我看了Lerp and Slerp Question,发现这几乎是同一个问题,但我已经拥有了这个人的答案。

1 个答案:

答案 0 :(得分:3)

这将是更像这样的事情

public IEnumerator MoveCameraLookAtObject(
   Transform _cameraTransform,
   Vector3 startPos, Vector3 endPos, Vector3 lookAt, float time)
{
float totalTime = 1.25f; // or whatever

float startTime = Time.time;
float endTime = startTime + totalTime;

startPos = etc etc
endPos = etc etc

startROTATION = ...
endROTATION = ...
// calculate those ONLY OUT HERE!!! not in the loop

while (Time.time < endTime)
  {
  float timeSoFar = Time.time - startTime;
  float fractionTime = timeSoFar/totalTime;

  //do NOT USE underscores in variable names
  cameraTransform.position =
    Vector3.Lerp(startPos, endPos, fractionTime);

  cameraTransform.rotation =
   Quaternion.Slerp(startROTATION, endROTATION, fractionTime);
  yield return null; // this goes IN HERE
  }
}

首先用JUST测试它,然后尝试扭转!干杯