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

Unity实现鼠标拖拽相机平滑旋转(含平滑释放)的技术问询

Unity 相机拖拽平滑旋转(带惯性)实现方案

要复刻拖拽后平滑减速的旋转效果,核心是记录拖拽时的鼠标移动惯性,并在释放后通过阻尼衰减让相机逐步停止。以下是修改后的完整代码及关键逻辑说明:

修改后的代码

using UnityEngine;

public class RotateCamera : MonoBehaviour
{
    [Header("旋转设置")]
    public float rotateSpeed = 3.5f;
    [Header("平滑阻尼")]
    public float dampTime = 0.15f; // 阻尼时间,越小停止越快

    private float targetX;
    private float targetY;
    private float mouseXVelocity;
    private float mouseYVelocity;

    void Start()
    {
        // 初始化目标角度为当前相机角度
        var currentEuler = transform.rotation.eulerAngles;
        targetX = currentEuler.x;
        targetY = currentEuler.y;
    }

    void LateUpdate()
    {
        if (Input.GetMouseButton(0))
        {
            // 拖拽时直接更新目标角度,用GetAxisRaw获取无平滑的鼠标输入
            targetX -= Input.GetAxisRaw("Mouse Y") * rotateSpeed;
            targetY += Input.GetAxisRaw("Mouse X") * rotateSpeed;
            
            // 限制X轴旋转范围(可选,防止相机翻转)
            targetX = Mathf.Clamp(targetX, -89f, 89f);
            
            // 更新惯性速度(用当前鼠标输入模拟)
            mouseXVelocity = Input.GetAxisRaw("Mouse X") * rotateSpeed * 10f;
            mouseYVelocity = -Input.GetAxisRaw("Mouse Y") * rotateSpeed * 10f;
        }
        else
        {
            // 释放鼠标后,通过阻尼衰减惯性速度,逐步趋近目标角度
            targetX = Mathf.SmoothDamp(targetX, targetX + mouseYVelocity * Time.deltaTime, ref mouseYVelocity, dampTime);
            targetY = Mathf.SmoothDamp(targetY, targetY + mouseXVelocity * Time.deltaTime, ref mouseXVelocity, dampTime);
            
            // 让惯性自然衰减,防止永远不停
            mouseXVelocity *= 0.9f;
            mouseYVelocity *= 0.9f;
            
            // 当速度足够小时直接停止
            if (Mathf.Abs(mouseXVelocity) < 0.1f && Mathf.Abs(mouseYVelocity) < 0.1f)
            {
                mouseXVelocity = 0;
                mouseYVelocity = 0;
            }
        }

        // 应用最终旋转
        transform.rotation = Quaternion.Euler(targetX, targetY, 0f);
    }
}

关键逻辑说明

  • 目标角度分离:用targetX和targetY存储相机要达到的最终旋转角度,代替直接修改transform.rotation,为平滑过渡提供基础。
  • 惯性记录:拖拽时用Input.GetAxisRaw获取无系统平滑的鼠标输入,计算并存储当前的移动速度作为惯性。
  • 阻尼衰减:释放鼠标后,通过Mathf.SmoothDamp函数实现目标角度的平滑过渡,同时逐步衰减惯性速度,模拟自然减速的效果。
  • 可选角度限制:代码中加入了X轴旋转范围的限制,避免相机翻转到不合理的角度,可根据需求调整或移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:30:36