using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// 摇杆
/// </summary>
public class Rocker : MonoBehaviour,IDragHandler,IEndDragHandler
{
public static Vector2 offset;//保存移动距离和方向
public RectTransform bar;//小圆
public RectTransform rocker;//大圆
public float r;//大圆半径
public float r1;//小圆半径
public void OnDrag(PointerEventData eventData)
{
Vector2 pos = eventData.position - rocker.anchoredPosition;
bar.anchoredPosition = Vector2.ClampMagnitude(pos,r-r1);
offset = bar.anchoredPosition / r;
}
public void OnEndDrag(PointerEventData eventData)
{
bar.anchoredPosition = Vector2.zero;
offset = Vector2.zero;
}
// Start is called before the first frame update
void Start()
{
r = rocker.rect.width < rocker.rect.height ? rocker.rect.width / 2 : rocker.rect.height / 2;
r1 = bar.rect.width < bar.rect.height ? bar.rect.width/2 : bar.rect.height/2;
}
}
![]()