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

Unity中通过鼠标拖拽实现GameObject沿X/Y/Z全轴平滑旋转的方法

全轴拖拽旋转+惯性停止实现方案

核心修改思路

  • 把原代码中仅支持Y轴的单轴速度变量替换为Vector3类型,同步存储X/Y/Z三个轴的旋转角速度
  • 拖拽阶段同时读取指针位移的X/Y分量,默认映射为:水平拖拽控制Y轴旋转、垂直拖拽控制X轴俯仰旋转,新增按住鼠标右键拖拽控制Z轴滚转的逻辑,可按需修改触发规则
  • 惯性阻尼阶段对三个轴的角速度统一做衰减处理,速度足够小时直接清零避免模型产生微小抖动

完整实现代码

using UnityEngine.EventSystems;
using UnityEngine;

public class RotateModel : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
    [Header("旋转参数")]
    public float rotationSpeed = 0.2f;
    public float rotationDamping = 10f;
    public KeyCode zRotationTriggerKey = KeyCode.Mouse1; // 默认右键触发Z轴旋转

    private Vector3 _rotationVelocity;
    private bool _dragged;

    public void OnBeginDrag (PointerEventData eventData) {
        _dragged = true;
    }

    public void OnDrag (PointerEventData eventData) {
        if (Input.GetKey(zRotationTriggerKey))
        {
            // 按住指定键时,水平拖拽控制Z轴滚转
            float zVel = eventData.delta.x * rotationSpeed;
            _rotationVelocity.z = Mathf.Clamp(zVel, -8f, 8f);
            transform.Rotate(Vector3.forward, -_rotationVelocity.z, Space.World);
        }
        else
        {
            // 正常拖拽:水平转Y轴,垂直转X轴
            float yVel = eventData.delta.x * rotationSpeed;
            float xVel = eventData.delta.y * rotationSpeed;
            _rotationVelocity.y = Mathf.Clamp(yVel, -8f, 8f);
            _rotationVelocity.x = Mathf.Clamp(xVel, -8f, 8f);
            transform.Rotate(Vector3.up, -_rotationVelocity.y, Space.World);
            transform.Rotate(Vector3.right, -_rotationVelocity.x, Space.World);
        }
    }

    public void OnEndDrag (PointerEventData eventData) {
        _dragged = false;
    }

    private void Update () {
        if (!_dragged && _rotationVelocity.magnitude > 0.01f)
        {
            // 角速度逐步衰减到0
            _rotationVelocity = Vector3.MoveTowards(_rotationVelocity, Vector3.zero, rotationDamping * Time.deltaTime);
            transform.Rotate(Vector3.up, -_rotationVelocity.y, Space.World);
            transform.Rotate(Vector3.right, -_rotationVelocity.x, Space.World);
            transform.Rotate(Vector3.forward, -_rotationVelocity.z, Space.World);
        }
        else if (_rotationVelocity.magnitude <= 0.01f)
        {
            _rotationVelocity = Vector3.zero;
        }
    }
}

参数调整说明

  • rotationSpeed:控制拖拽时的旋转灵敏度,数值越大旋转速度越快
  • rotationDamping:控制惯性衰减速度,数值越大松开鼠标后旋转停止得越快,数值越小惯性滑行时间越长
  • zRotationTriggerKey:可自定义Z轴旋转的触发按键,不需要Z轴旋转功能直接删除对应判断逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:57:05