【发布时间】:2021-04-22 23:25:52
【问题描述】:
到目前为止学习统一,用鼠标旋转相机是给我最多的问题。现在我面临的问题是,在制作基于刚体的第一人称控制器时,角色和相机与鼠标的旋转不一致且抖动。
这个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。对相机移动的流畅度没有影响。
- 垂直旋转。加了太多延迟,好像真的不适合FPS控制器?我该如何应对偏航?
- 将旋转从 FixedUpdate 移动到 Update。不做任何事情,我们正在编辑刚体,因此最好在 fixedUpdate 上执行所有其他与物理相关的计算。
- 制作单独的组件,一个用于旋转,另一个用于移动。也无济于事。
有时在模拟的前几秒我确实可以顺利运行,但过了一会儿它又变得不稳定了。
我真的不知道如何解决它/导致问题的原因。如果您能帮我解决这个问题或让我走上正确的道路来理解问题,我将不胜感激。
提前感谢您帮助我。
【问题讨论】:
-
尝试将相机移动放入
LateUpdate()。我不确定您给定代码的结果,因为我不知道整个项目是如何设置的,但这可能会有所帮助。另一件事是所有输入代码都应该在Update()而不是FixedUpdate()。仅对FixedUpdate()使用物理计算。我会将您的输入作为变量存储在Update()中,在FixedUpdate()中更新您的动作并在LateUpdate()中更新相机。 -
@TEEBQNE 感谢您的建议!它确实降低了抖动效果并为脚本执行添加了更好的顺序,谢谢!