Unity中基于触摸输入的幸运轮盘旋转实现
Unity 触摸拖动控制幸运轮盘旋转实现方案
核心逻辑很直白:捕捉触摸拖动的速度,将其转换成轮盘的旋转角速度,再通过物理组件模拟惯性减速,还原现实转盘的手感。下面是分步实现步骤:
1. 轮盘对象基础设置
- 给轮盘添加
Rigidbody2D(2D场景)或Rigidbody(3D场景):- 把重力设为0,避免重力干扰旋转
- 开启冻结位置(只保留旋转自由度)
- 调整
Angular Drag(角阻力):值越大,转盘减速越快,推荐设为1-5,模拟现实摩擦效果
- 给轮盘添加合适的Collider(2D用
CircleCollider2D,3D用SphereCollider或MeshCollider),确保能准确检测触摸区域
2. 触摸拖动与旋转逻辑实现
下面是2D版本的完整代码,直接挂在轮盘对象上即可:
using UnityEngine; public class WheelDragController : MonoBehaviour { private Rigidbody2D _wheelRb; private Vector2 _lastTouchWorldPos; private bool _isDraggingWheel; void Awake() { _wheelRb = GetComponent<Rigidbody2D>(); // 初始化物理参数 _wheelRb.gravityScale = 0; _wheelRb.constraints = RigidbodyConstraints2D.FreezePosition; } void Update() { if (Input.touchCount == 0) return; Touch currentTouch = Input.GetTouch(0); Vector2 touchWorldPos = Camera.main.ScreenToWorldPoint(currentTouch.position); switch (currentTouch.phase) { case TouchPhase.Began: // 检查触摸是否命中轮盘 if (GetComponent<Collider2D>().OverlapPoint(touchWorldPos)) { _isDraggingWheel = true; _lastTouchWorldPos = touchWorldPos; // 拖动开始时停止惯性旋转 _wheelRb.angularVelocity = 0; } break; case TouchPhase.Moved: if (_isDraggingWheel) { // 计算触摸位移差,转换成旋转角度 Vector2 deltaPos = touchWorldPos - _lastTouchWorldPos; float deltaAngle = Mathf.Atan2(deltaPos.y, deltaPos.x) - Mathf.Atan2(_lastTouchWorldPos.y - transform.position.y, _lastTouchWorldPos.x - transform.position.x); // 直接旋转轮盘 transform.Rotate(0, 0, deltaAngle * Mathf.Rad2Deg); _lastTouchWorldPos = touchWorldPos; } break; case TouchPhase.Ended: if (_isDraggingWheel) { _isDraggingWheel = false; // 把触摸结束时的速度转换成轮盘角速度 Vector2 touchSpeed = currentTouch.deltaPosition / Time.deltaTime; // 这里的0.5f是适配系数,根据你的轮盘大小/屏幕调整 float angularVelocity = touchSpeed.magnitude * 0.5f; // 保持旋转方向和拖动方向一致 _wheelRb.angularVelocity = angularVelocity * Mathf.Sign(touchSpeed.x); } break; } } }
3. 手感调优技巧
- 适配系数调整:代码里的
0.5f是拖动速度到旋转速度的转换系数,觉得拖动太灵敏或太迟钝,直接改这个值就行 - 角阻力微调:转盘停得太快就减小
Angular Drag,停得太慢就增大它 - 3D场景适配:把
Rigidbody2D换成Rigidbody,旋转代码改成transform.Rotate(Vector3.up, deltaAngle * Mathf.Rad2Deg),触摸检测用Physics.Raycast代替OverlapPoint - 误触避免:不想让轮盘边缘触发拖动的话,可以缩小Collider范围,或者单独做一个中心触发区域
内容的提问来源于stack exchange,提问作者VeN0K
相关产品推荐
相关产品推荐

