当我在Unity中使对象面对鼠标光标时,它最终会偏移

问题描述

我制作了一个脚本,使播放器指向鼠标光标,但是最近我发现了一个错误。当我将鼠标光标移动得太多时(例如,当我将鼠标绕着对象旋转时,导致对象四处移动。),对象最终指向鼠标应离开的位置。如图所示,光标将发出信号通知对象看它,并且该对象最终看起来几乎没有一点,使其在快速操纵后感觉很奇怪。如何使对象始终始终面对光标,而没有没有偏移,即使我尽可能多地移动光标也是如此。

            private void LateUpdate()
{
    Vector3 lookAtPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector3 mousePoint = new Vector3(lookAtPoint.x,lookAtPoint.y,0);

    float angle = getAngle(transform.position,mousePoint);
    transform.rotation = Quaternion.Lerp(transform.rotation,Quaternion.Euler(0,angle),9f * Time.deltaTime);

    float getAngle(Vector3 currentLocation,Vector3 mouseLocation)
    {
        float x = mouseLocation.x - currentLocation.x;
        float y = mouseLocation.y - currentLocation.y;

        return angle = Mathf.Rad2Deg * Mathf.atan2(y,x);

    }
}

解决方法

似乎取决于您使用Quaternion.Lerp()的方式。特别是最后一个参数-它是您提供的介于0f和1f之间的值,不会为您自动递增。

因此,要解决此问题,您要做的是将浮点数保存在某个地方。当您移动鼠标(自上一帧以来鼠标位置已改变)时,请再次从0f开始该值。然后每帧以某个值递增它,直到等于或大于1f。

这样做不仅可以解决您的错误。根据增加的快慢,它会为您带来平滑的旋转效果。下面是一个示例。

internal class SomeClass : MonoBehaviour
{
  private float lerpAmount = 0f;
  private Vector3 cachedMousePosition = Vector3.zero;
  
  private void LateUpdate()
  {
    var mousePosition
      = Camera.main.ScreenToWorldPoint(Input.mousePosition)
      * new Vector3(1,1,0);
    
    bool recalculateRotation = false;
    if (this.cachedMousePosition != mousePosition)
    {
      this.lerpAmount = 0f;
      recalculateRotation = true;
    }

    if (this.lerpAmount < 1f)
    {
      this.lerpAmount = Mathf.Min(this.lerpAmount + Time.deltaTime,1f);
      recalculateRotation = true;
    }

    if (recalculateRotation)
    {
      float angle = getAngle(transform.position,mousePoint);
      transform.rotation = Quaternion.Lerp(transform.rotation,Quaternion.Euler(0,angle),this.lerpAmount);
    }

    float getAngle(Vector3 currentLocation,Vector3 mouseLocation)
    {
      float x = mouseLocation.x - currentLocation.x;
      float y = mouseLocation.y - currentLocation.y;

      return angle = Mathf.Rad2Deg * Mathf.Atan2(y,x);

    }
  }