c# - 向相机方向旋转第三人称?
问题描述
我希望我的对象在我旋转相机的同时朝向相机旋转,这样玩家在行走时总是朝向相机的方向,就像在典型的第三人称游戏中一样。不幸的是,到目前为止使用的任何方法都会使我旋转物体,稍微落后于相机的旋转。我一直在寻找一个星期的解决方案,我很绝望。我发布了我与一个对象的旋转视频。
private Rigidbody rb;
public float speed = 1.0f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
direction = Camera.main.transform.forward;
direction.y = 0.00f;
private void FixedUpdate ()
{
Quaternion targetRotation = Quaternion.LookRotation(direction);
Quaternion newRotation = Quaternion.Lerp(rb.transform.rotation, targetRotation, speed * Time.fixedDeltaTime);
rb.MoveRotation(newRotation);
}
}
解决方案
这是一个不合适的用途,Quaternion.Lerp
因为您没有按比例计算要移动的距离。目前,您基本上是在告诉它只旋转一小部分到目标旋转的方式。
您应该使用Quaternion.RotateTowards
,因为您可以轻松地根据deltaTime
(或者,fixedDeltaTime
当您使用)计算角度旋转:
public float speed = 30f; // max rotation speed of 30 degrees per second
// ...
Quaternion newRotation = Quaternion.RotateTowards(rb.transform.rotation, targetRotation,
speed * Time.deltaTime);
rb.MoveRotation(newRotation);
重新阅读您的问题后,现在您似乎不想要平稳过渡/ lerp。在这种情况下,只需将旋转设置为目标旋转:
rb.MoveRotation(targetRotation);
如果即使插值过多/不够直接,您也可以将刚体的旋转设置为Update
:
private void Update ()
{
rb.rotation = Quaternion.LookRotation(direction);
}