到目前为止,学习 Unity 时,用鼠标旋转相机是给我带来最多问题的事情。现在我面临的问题是,在制作基于刚体的第一人称 Controller 时,角色和相机随着鼠标的旋转不一致并且抖动。
这个youtube video ,显示了问题。在其中,我平稳地移动鼠标,但旋转似乎有时会跳过一些中间旋转并跳转到新值。
这是脚本的完整代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody), typeof(Collider))]
public class CompleteRBController : MonoBehaviour
{
[Header("Referenced components:")]
[SerializeField]
private Rigidbody _rb;
[SerializeField]
private Transform _cameraTransform;
[Header("Mouse Settings")]
public float _mouseSensitivity = 100f;
[SerializeField]
private float pitch = 0f;
[SerializeField]
private bool _mouseInverted = false;
[Header("Parameters:")]
[SerializeField]
private float _speed = 10f;
[SerializeField]
private float _sprintSpeed = 15f;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update()
{
}
private void FixedUpdate()
{
//Get input mouse
float mouseX = Input.GetAxisRaw("Mouse X") * _mouseSensitivity * Time.fixedDeltaTime;
float mouseY = Input.GetAxisRaw("Mouse Y") * _mouseSensitivity * Time.fixedDeltaTime;
//Get input keyboard
float vertical = Input.GetAxisRaw("Vertical");
float horizontal = Input.GetAxisRaw("Horizontal");
// Debug.Log(string.Format("Vertical: {0}, Horizontal: {1}", vertical, horizontal));
bool isSprinting = Input.GetKey(KeyCode.LeftShift);
//Rotate
pitch += (_mouseInverted) ? -mouseY : mouseY;
pitch = Mathf.Clamp(pitch, -89, 89);
_cameraTransform.localRotation = Quaternion.Euler(pitch, 0, 0);
transform.Rotate(transform.up * mouseX);
//Move
Vector3 move = (transform.forward * vertical + transform.right * horizontal).normalized * ((isSprinting)? _sprintSpeed : _speed);
_rb.velocity = new Vector3(move.x, _rb.velocity.y, move.z);
}
}
我还将添加我尝试更改的内容列表,以使其顺利进行:
- 用 getAxis 更改 getAxisRaw。不影响相机移动的流畅性。
- Lerping 垂直旋转。增加太多延迟,似乎不太适合 FPS Controller ?我该如何消除偏航?
- 将轮换从固定更新移至更新。不执行任何操作,并且我们正在编辑刚体,因此最好在固定更新上与所有其他物理相关的计算一起执行此操作。
- 制作单独的组件,一个用于旋转,另一个用于移动。也没有帮助。
有时在模拟的最初几秒我确实工作顺利,但过了一会儿又变得不稳定。
我真的不知道如何解决它/是什么导致了这个问题。如果您能帮助我解决这个问题或让我走上理解问题的正确轨道,我将不胜感激。
预先感谢您对我的帮助。
最佳答案
只要FixedUpdate 与帧/Update() 的更新不匹配,就会发生跳过。这就是为什么您应该将所有与输入相关的内容放在“更新”中,将所有与物理相关的内容放在“固定更新”中。我建议您创建一个Inputmanager方法和一个CalculateMovement方法。然后将Inputmanager方法放在Update中,将CalculateMovement方法放在FixedUpdate中。另外,Time.fixedDeltaTime 与 Time.DeltaTime 不同。 如果您将输入放在Update而不是FixedUpdate中,则必须将其更改为Time.DeltaTime。希望我可以帮助您! :)
关于c# - Unity 相机旋转与鼠标不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67222028/