Unity 相机围绕物体旋转平稳停止

Unity camera rotation around object to a smooth stop

我有一个脚本可以让我的相机在按下右键时围绕目标旋转。目前,当释放右键时,旋转完全停止,这是完全预期的行为。我希望它在鼠标按钮抬起后继续旋转一会儿,然后完全停止,就像它正在减速一样。这是处理给定目标周围旋转的代码:

            if (!target)
                return;

            if (Input.GetMouseButtonDown(1))
                previousPosition = cam.ScreenToViewportPoint(Input.mousePosition);

            if (Input.GetMouseButton(1))
            {
                Vector3 nextDirection = previousPosition - cam.ScreenToViewportPoint(Input.mousePosition);
                direction = Vector3.SmoothDamp(direction, nextDirection, ref smoothVelocity, smoothTime);
                cam.transform.position = target.position;
                cam.transform.Rotate(new Vector3(1, 0, 0), direction.y * 180);
                cam.transform.Rotate(new Vector3(0, 1, 0), -direction.x * 180, Space.World);
                cam.transform.Translate(new Vector3(0, 0, -distanceFromSphere));

                previousPosition = cam.ScreenToViewportPoint(Input.mousePosition);
            }

这里是需要的参考资料:

  public Camera cam;
  public Vector3 previousPosition;
  public Transform target;
  public float distanceFromSphere = 100;
  public Vector3 direction;
  public Vector3 smoothVelocity = Vector3.zero;
  public float smoothTime = 3f;

有没有什么办法可以让相机的旋转在鼠标按下时加速,而在鼠标弹起时减速?

你需要的是惯性,在 if 语句之外获取 Rotate 和 Translate 调用,最后根据你需要多少惯性将方向乘以 0.98 或 0.99。

public float inertia = 0.98f;


direction *= inertia;

Chris Ch 的解决方案工作正常,但我已经做了一些不同的事情,这是我对原始问题的解决方案:

void UpdateWorldRotation()
        {
            if (!target)
                return;

            if (Input.GetMouseButtonDown(1))
                previousPosition = cam.ScreenToViewportPoint(Input.mousePosition);

            Vector3 currentSmoothVelocity = new Vector3();
            if (Input.GetMouseButton(1))
            {
                nextDirection = previousPosition - cam.ScreenToViewportPoint(Input.mousePosition);
                currentSmoothVelocity = smoothVelocity;
            }
            if (Input.GetMouseButtonUp(1))
            {
                StartCoroutine(SmoothStop());
                currentSmoothVelocity = smoothVelocity / 2;
            }

            direction = Vector3.SmoothDamp(direction, nextDirection, ref currentSmoothVelocity, smoothTime, 100, 10f * Time.deltaTime);
            cam.transform.position = target.position;
            cam.transform.Rotate(new Vector3(1, 0, 0), direction.y * 180);
            cam.transform.Rotate(new Vector3(0, 1, 0), -direction.x * 180, Space.World);
            cam.transform.Translate(new Vector3(0, 0, -distanceFromSphere));

            previousPosition = cam.ScreenToViewportPoint(Input.mousePosition);

        }

        IEnumerator SmoothStop()
        {
            yield return new WaitForSeconds(smoothStopTime);
            nextDirection = Vector3.zero;
        }

这样,球体在完全停止之前以较慢的速度持续旋转特定的时间。