public class Joystick : MonoBehaviour,IDragHandler,IPointerDownHandler,IPointerUpHandler {
[SerializeField]
private RectTransform borderTF;
[SerializeField]
private RectTransform handleTF;
private float range;
[SerializeField]
private AnimationCurve curve;
private Vector2 endDragPosition;
private float totlalTime;
private bool isEndDrag;
public Vector2 direction;
void Start () {
range = Mathf.Max(borderTF.rect.width,borderTF.rect.height) / 2;
//获取遥控点的父物体大小,限制遥控点的移动范围
}
void Update () {
Homing ();
}
private void Homing()
{
if (!isEndDrag) return;
totlalTime += Time.deltaTime;
handleTF.localPosition = Vector3.LerpUnclamped(endDragPosition,Vector3.zero,curve.Evaluate(totlalTime));//利用AnimationCurbe控制遥控点的回归曲线
if(totlalTime >= 1)
{
isEndDrag = false;
totlalTime = 0;
}
}
public void OnDrag (PointerEventData eventData)
{
isEndDrag = false;
Vector2 local;
RectTransformUtility.ScreenPointToLocalPointInRectangle (handleTF,eventData.position,eventData.enterEventCamera,out local);//将摇杆控制点的屏幕坐标转换为自身坐标
handleTF.localPosition = Vector2.ClampMagnitude (local,range);//设置自身坐标在某个范围内
}
public void OnPointerDown (PointerEventData eventData)
{
}
public void OnPointerUp (PointerEventData eventData)
{
isEndDrag = true;
endDragPosition = handleTF.localPosition;
}
注意点就是要想监听到OnPionterUp事件,必须要实现IPointerDownHandler接口,只有鼠标有Down,才会有Up.