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

Unity中如何实现平滑滚轮缩放?

平滑滚轮相机缩放实现方案

你当前的缩放效果生硬,核心原因是直接瞬间修改相机的orthographicSize,没有过渡动画。要实现平滑效果,思路是维护一个目标缩放尺寸,每帧通过插值让当前尺寸向目标值靠近,同时同步调整相机位置,保证鼠标指向的世界位置不会偏移。

修改后的完整代码

// 新增变量:目标正交尺寸、平滑速度、鼠标基准世界位置
private float targetOrthographicSize;
public float smoothZoomSpeed = 5f;
private Vector3 targetMouseWorldPos;

void Start()
{
    // 初始化目标尺寸为相机当前尺寸
    targetOrthographicSize = Camera.main.orthographicSize;
}

private void Zoom(float zoomDiff)
{
    if (zoomDiff != 0)
    {
        // 计算并限制新的目标缩放尺寸
        float newTargetSize = Mathf.Clamp(targetOrthographicSize - zoomDiff * zoomScale, zoomMin, zoomMax);
        // 仅当目标尺寸变化时,记录当前鼠标指向的世界位置
        if (newTargetSize != targetOrthographicSize)
        {
            targetOrthographicSize = newTargetSize;
            targetMouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        }
    }
}

void Update()
{
    Zoom(Input.GetAxis("Mouse ScrollWheel"));

    // 平滑过渡相机尺寸,避免微小抖动加了阈值判断
    if (Mathf.Abs(Camera.main.orthographicSize - targetOrthographicSize) > 0.01f)
    {
        Camera.main.orthographicSize = Mathf.Lerp(Camera.main.orthographicSize, targetOrthographicSize, smoothZoomSpeed * Time.deltaTime);
        
        // 同步调整相机位置,保证鼠标指向的物体不偏移
        Vector3 currentMouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position += targetMouseWorldPos - currentMouseWorldPos;
    }
}

关键改动说明

  • targetOrthographicSize:存储最终要达到的缩放尺寸,不再直接修改相机当前尺寸
  • Mathf.Lerp + Time.deltaTime:实现线性平滑过渡,smoothZoomSpeed控制缩放快慢,数值越大过渡越快
  • 鼠标位置同步:只有目标尺寸变化时记录基准鼠标位置,每帧通过位置差调整相机,保证缩放时鼠标焦点不变
  • 阈值判断:避免相机尺寸在目标值附近反复微小抖动

进阶缓动效果(可选)

如果想要更自然的“先快后慢”缓动,可以把Mathf.Lerp换成Mathf.SmoothDamp,需要额外加一个速度变量:

private float zoomVelocity;

// 替换Update里的Lerp代码
Camera.main.orthographicSize = Mathf.SmoothDamp(Camera.main.orthographicSize, targetOrthographicSize, ref zoomVelocity, 0.1f);

这里的0.1f是平滑时间,数值越小过渡越快,可根据需求调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:42:45