比如音响的音量旋钮
具体逻辑:鼠标按下时期间每帧记录鼠标位置,算出由2D物体中心到鼠标的向量角度,根据角度变化相等地调节2D物体的旋转。
缺点:无法记录拖拽转了几圈
代码:
csharp
using UnityEngine;
using UnityEngine.EventSystems;
public class knob : MonoBehaviour, IBeginDragHandler, IDragHandler
{
Vector2 knobPos;
RectTransform knobRT;
float rotAngle = 0;
float angleRecord = 0;
float clickRecord = 0;
private void Start()
{
knobPos = RectTransformUtility.WorldToScreenPoint(null,transform.position);
knobRT = GetComponent<RectTransform>();
}
public void OnBeginDrag(PointerEventData eventData)
{
angleRecord = knobRT.localEulerAngles.z;
clickRecord = Vector2Angle(Input.mousePosition);
}
public void OnDrag(PointerEventData eventData)
{
rotAngle = Vector2Angle(Input.mousePosition);
//Debug.Log(rotAngle);
knobRT.localEulerAngles = new Vector3(0, 0, angleRecord + rotAngle - clickRecord);
}
float Vector2Angle(Vector2 vector)
{
return Mathf.Atan2(vector.y - knobPos.y, vector.x - knobPos.x) / Mathf.PI * 180;
}
}