当我在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, 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);
}
}

看起来这取决于您使用四元数.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, 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);
}
}

最新更新