Unity 使鼠标看起来流畅且与帧速率无关

Unity get mouselook to be smooth and framerate independent

对于这种情况,我一直对 Update()FixedUpdate()time.deltaTimetime.fixedDeltaTime 感到困惑。

我希望相机鼠标外观的帧速率独立移动,但同时我希望它在 60 fps 下尽可能平滑。出于某种原因,60 fps 似乎有点紧张。

我的问题是,我是将下面的函数放在 Update() 还是 FixedUpdate() 中? deltaTime 变量应该是 time.deltaTime 还是 time.fixedDeltaTime 来实现这个?还是我做错了?

感谢任何意见。

顺便说一句,下面的 SmoothDamp 函数是一个基于 lerp 的平滑函数,它允许反馈

void MouseLook()
{
    if (_isEscaped)
        return;

    if (!_isAllowedToLook)
        return;

    var deltaTime = Time.fixedDeltaTime;

    var adjustedSensitivity = _lookSensitivity * 100f; //Keeps sensitivity between 0.1 and 10f but makes the sensitivity in math actually work

    _lookInput.x = SmoothDamp.Float(_lookInput.x, Input.GetAxis("Mouse X"), _lookSmoothSpeed, deltaTime);
    _lookInput.y = SmoothDamp.Float(_lookInput.y, Input.GetAxis("Mouse Y"), _lookSmoothSpeed, deltaTime);

    // Mouse look
    var newVerticalPitch = _verticalPitch + _lookInput.y * -adjustedSensitivity * deltaTime;
    _verticalPitch = SmoothDamp.Float(_verticalPitch, newVerticalPitch, 15f, deltaTime);
    _verticalPitch = Mathf.Clamp(_verticalPitch, -_maxVerticalLookAngle, _maxVerticalLookAngle);             //Clamp vertical look

    // Camera vertical rotation
    var newCameraRotation = Quaternion.Euler(Vector3.right * _verticalPitch);
    _camTransform.localRotation =
        SmoothDamp.Quaternion(_camTransform.localRotation, newCameraRotation, 15f, deltaTime);


    // Player horizontal rotation
    var newPlayerRotation = _transform.rotation * Quaternion.Euler(_lookInput.x * adjustedSensitivity * deltaTime * Vector3.up);
    _transform.rotation = SmoothDamp.Quaternion(_transform.rotation, newPlayerRotation, 15f, deltaTime); //Player rotation
}

Update and FixedUpdate 都是 Unity 在其生命周期中的特定时间对您的 Monobehaviours 调用的回调函数。更具体地说,Update 被称为 每一帧 (假设 Monobehaviour 已启用)并且 FixedUpdate 被称为 每一物理帧

物理帧独立于图形帧率,并从 Unity 内部设置为以特定间隔发生。默认值为每秒 50 次(换句话说,默认情况下 FixedUpdate 运行s 50fps)。

FixedUpdate 通常是您应该为 基于物理的需求(例如使用 RigidBodies 或光线投射等)保留的功能并且肯定不是用于诸如获取用户输入之类的事情。

现在希望解决这个问题,让我们解决 Time.deltaTimeTime.fixedDeltaTime:

Time.fixedDeltaTime returns 自前一 FixedUpdate() 帧以来经过的时间量 运行。现在,由于我们从上面知道 FixedUpdate() 运行s 在恒定帧速率(默认情况下为 50)下,此值在帧之间或多或少总是相同

Time.deltaTime 同样地 returns 自前一个 Update() 帧以来经过的时间量 运行。现在,由于 Update() 在恒定帧速率下 而不是 运行,但取决于用户的机器,因此该值几乎总是会有点每一帧都不一样。

所以考虑到所有这些,它应该放在 Update() 还是 FixedUpdate() 中?它应该使用 Time.deltaTime 还是 Time.fixedDeltaTime

如果我已经很好地解释了这些东西之间的区别,那么我希望您现在知道它应该进入 Update() 并使用 Time.deltaTime.

我不知道 SmoothDamp.Float() 方法到底在做什么,但是通过 lerping 在两个位置之间使用 Time.deltaTime 作为 t 参数,您将确保无论机器 运行ning 的帧速率是多少,它都会流畅且一致。