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

Unity车辆选择界面:实现相机松开鼠标后的平滑减速停止(无需Cinemachine)

实现带惯性的相机环绕旋转效果

要实现松开鼠标后相机缓慢减速停止的效果,核心是记录鼠标拖动时的旋转速度,然后在松开鼠标后让这个速度逐渐衰减,直到趋近于0。不用Cinemachine完全可以手动实现,我帮你修改代码并解释关键逻辑:

修改后的完整代码

public class MenuCameraMovement : MonoBehaviour 
{
    public Transform car;
    public float sensitivity = 2f;
    // 减速速率,值越大减速越平缓,建议设为0.9~0.98之间
    public float decelerationRate = 0.95f;
    // 速度阈值,低于这个值就停止旋转,避免微小抖动
    public float stopThreshold = 0.01f;
    
    private float currentHorizontalSpeed;

    private void Update() 
    {
        if (Input.GetMouseButton(0)) 
        {
            float rotateHorizontal = Input.GetAxis("Mouse X");
            // 记录当前的旋转速度(鼠标输入 * 灵敏度)
            currentHorizontalSpeed = rotateHorizontal * sensitivity;
            // 执行即时旋转
            transform.RotateAround(car.position, Vector3.up, currentHorizontalSpeed);
        }
        else
        {
            // 松开鼠标后,让速度逐渐衰减
            if (Mathf.Abs(currentHorizontalSpeed) > stopThreshold)
            {
                currentHorizontalSpeed *= decelerationRate;
                // 用衰减后的速度继续旋转相机
                transform.RotateAround(car.position, Vector3.up, currentHorizontalSpeed);
            }
            else
            {
                // 速度低于阈值时直接归零,避免持续微小旋转
                currentHorizontalSpeed = 0;
            }
        }
    }
}

关键逻辑说明

  • currentHorizontalSpeed:用来存储当前相机的旋转速度,按住鼠标时直接用鼠标输入更新这个值。
  • decelerationRate:控制减速的快慢,比如设为0.95的话,每帧速度会变成上一帧的95%,越接近1减速越平缓,越接近0减速越快。
  • stopThreshold:当速度小于这个值时直接停止旋转,防止相机因为微小的速度持续抖动。
  • 松开鼠标后的逻辑:只要速度还没降到阈值以下,就持续用衰减后的速度旋转相机,直到速度归零。

你可以根据实际体验调整sensitivity、decelerationRate和stopThreshold这三个参数,找到最舒服的手感~

内容的提问来源于stack exchange,提问作者ouzdmrkl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:39:05