Unity中OnMouseDrag触发但Input.GetMouseButtonDown全返回false的问题
问题描述
在Unity场景中放置了一个简单3D物体,挂载脚本实现鼠标拖拽让物体在3D空间自由旋转,脚本代码如下:
float rotationSpeed = 6; private void OnMouseDrag() { Debug.Log(Input.GetMouseButtonDown(0) + " 0"); Debug.Log(Input.GetMouseButtonDown(1) + " 1"); Debug.Log(Input.GetMouseButtonDown(2) + " 2"); if(Input.GetMouseButtonDown(0)) { updatePrimitiveRotation(); } } private Vector2 getDragAmount() { Vector2 dragAmount = new Vector2(Input.GetAxis("Mouse X") * rotationSpeed, Input.GetAxis("Mouse Y") * rotationSpeed); return dragAmount; } private void updatePrimitiveRotation() { Vector2 drag = getDragAmount(); gameObject.transform.Rotate(Vector3.down, drag.x, Space.World); gameObject.transform.Rotate(Vector3.right, drag.y, Space.World); }
遇到的问题:
- OnMouseDrag可以正常触发,但物体完全无法旋转;
- 添加日志后发现,
Input.GetMouseButtonDown(0/1/2)始终返回false; - 只有左键能触发OnMouseDrag,右键无法触发该函数,但三条日志依旧全为
false。
问题分析与修复方案
核心问题1:错误使用Input.GetMouseButtonDown
OnMouseDrag函数的触发逻辑是:当按住鼠标左键拖拽物体时,每帧都会调用一次。而Input.GetMouseButtonDown(0)仅在鼠标左键按下的第一帧返回true,后续拖拽过程中该值一直是false,导致updatePrimitiveRotation()永远不会被执行,这就是物体不旋转的根本原因。
核心问题2:OnMouseDrag默认仅响应左键
Unity的OnMouseDrag是内置鼠标事件,默认只绑定左键操作,右键无法触发该函数,所以右键拖拽时完全没反应。
修复后的代码(仅支持左键拖拽旋转)
直接去掉Input.GetMouseButtonDown(0)的判断,在OnMouseDrag中直接调用旋转逻辑即可:
float rotationSpeed = 6; private void OnMouseDrag() { updatePrimitiveRotation(); } private Vector2 getDragAmount() { Vector2 dragAmount = new Vector2(Input.GetAxis("Mouse X") * rotationSpeed, Input.GetAxis("Mouse Y") * rotationSpeed); return dragAmount; } private void updatePrimitiveRotation() { Vector2 drag = getDragAmount(); // 可根据需求调整旋转轴和空间,比如改用Space.Self可能更符合直觉 gameObject.transform.Rotate(Vector3.down, drag.x, Space.World); gameObject.transform.Rotate(Vector3.right, drag.y, Space.World); }
扩展:支持右键拖拽旋转
如果需要右键也能触发旋转,放弃OnMouseDrag,改用Update函数监听鼠标按键状态:
float rotationSpeed = 6; private void Update() { // 左键拖拽旋转 if (Input.GetMouseButton(0)) { updatePrimitiveRotation(); } // 右键拖拽旋转(可单独调整逻辑,比如反转旋转方向) else if (Input.GetMouseButton(1)) { Vector2 drag = getDragAmount(); gameObject.transform.Rotate(Vector3.down, -drag.x, Space.World); gameObject.transform.Rotate(Vector3.right, -drag.y, Space.World); } } private Vector2 getDragAmount() { Vector2 dragAmount = new Vector2(Input.GetAxis("Mouse X") * rotationSpeed, Input.GetAxis("Mouse Y") * rotationSpeed); return dragAmount; } private void updatePrimitiveRotation() { Vector2 drag = getDragAmount(); gameObject.transform.Rotate(Vector3.down, drag.x, Space.World); gameObject.transform.Rotate(Vector3.right, drag.y, Space.World); }
额外注意事项
- 确保3D物体上挂载了
Collider组件,Unity的鼠标事件(如OnMouseDrag)需要依赖碰撞体才能触发; - 触控板操作下,
Input.GetAxis("Mouse X/Y")同样可以正常获取位移,无需额外适配。
内容的提问来源于stack exchange,提问作者Ash10
相关产品推荐
相关产品推荐

