You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity3D中如何解决鼠标输入抖动问题?

Unity3D中如何解决鼠标输入抖动问题?

嘿,我看了你的问题和代码,发现几个关键问题导致了这些奇怪的鼠标旋转异常,咱们一步步来解决:

  • 先修正代码里的低级拼写错误:你在Update()方法里写的nouseSensitivity是拼写错误,应该是mouseSensitivity!这个错误会直接导致mouseX和mouseY的值计算错误,甚至垂直方向输入直接失效,这也是你提到的“垂直鼠标输入/rotation no longer works”的核心原因之一。

  • Time.deltaTime的正确使用姿势:你之前尝试加Time.deltaTime的位置不对,才会出现横竖旋转速度不一致的情况。正确的做法是在获取鼠标输入的同时就统一乘以mouseSensitivity * Time.deltaTime,这样旋转速度会基于时间而非帧率,不管游戏帧率高低,鼠标旋转的速度都会保持稳定一致。

  • 旋转逻辑的一致性调整:你之前的水平旋转直接用未做时间缩放的inputVector.x去旋转玩家身体,而垂直旋转是累积基于输入的cameraPitch,两者的时间基准不统一,自然会出现一快一慢的问题。咱们要让横竖旋转都基于相同的时间缩放规则。

下面是修正后的完整代码,我标注了关键改动:

using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
    // Camera rotation variables
    public float mouseSensitivity = 200f; // 因为加了Time.deltaTime,这里需要把灵敏度调大一些,比如200f是比较合适的数值
    public float topAngleLimit = 80.0f;
    public float bottomAngleLimit = -45.0f;
    private Vector2 inputVector;
    public float cameraPitch = 0.0f;

    public Transform mainCamera;

    //public float horizontalRecoilOffset = 0f;
    public Transform playerBody; // 把玩家主父物体拖到这个Inspector插槽里

    [SerializeField] private WeaponManager weaponManager; 
    public Aiming aim;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;      
    }

    void Update()
    {
        // 1. 修正拼写错误,同时统一乘以Time.deltaTime
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        inputVector = new Vector2(mouseX, mouseY);

        CameraRotation(); 
    }

    private void CameraRotation()
    {
        // 调整垂直/俯仰角
        cameraPitch -= inputVector.y;
        cameraPitch = ClampAngle(cameraPitch, bottomAngleLimit, topAngleLimit);

        // 应用垂直旋转到相机
        mainCamera.localRotation = Quaternion.Euler(cameraPitch, 0.0f, 0.0f); // 这里注释掉了horizontalRecoilOffset,如果你需要后坐力可以再加回去,但要确保它的逻辑也统一

        // 旋转玩家身体处理水平偏航
        playerBody.Rotate(Vector3.up * inputVector.x); // 直接用已经做了时间缩放的inputVector.x
    }

    public static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360f) angle += 360f;
        if (angle > 360f) angle -= 360f;
        return Mathf.Clamp(angle, min, max);
    }
}

额外说明:

  • 因为加了Time.deltaTime,鼠标灵敏度需要适当调大(比如从2f改成200f),这样旋转速度才会和你之前的2f效果接近。
  • 如果你需要恢复horizontalRecoilOffset的功能,建议把它也做成基于时间的增量,避免和鼠标旋转的速度基准冲突。

备注:内容来源于stack exchange,提问作者RelevantUni98

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 10:49:34