ParticleEffectForUGUI/Samples~/Demo/Scripts/UIElementDragger.cs

94 lines
2.5 KiB
C#
Raw Normal View History

2024-01-23 22:17:57 +08:00
using System;
2023-08-17 08:43:02 +08:00
using UnityEngine;
2022-06-09 00:50:36 +08:00
using UnityEngine.EventSystems;
2023-08-17 08:43:02 +08:00
using UnityEngine.Serialization;
2022-06-09 00:50:36 +08:00
public class UIElementDragger : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
2023-08-17 08:43:02 +08:00
[SerializeField]
private Target m_Target;
2022-06-09 00:50:36 +08:00
2023-08-17 08:43:02 +08:00
[SerializeField]
private Transform m_CustomTarget;
[FormerlySerializedAs("ex2")]
[SerializeField]
private bool m_UseCanvasScale;
private Canvas _canvas;
private RectTransform _rectTransform;
2022-06-09 00:50:36 +08:00
private void OnEnable()
{
2023-08-17 08:43:02 +08:00
_rectTransform = GetComponent<RectTransform>();
_canvas = GetComponentInParent<Canvas>();
}
public void OnBeginDrag(PointerEventData eventData)
{
2022-06-09 00:50:36 +08:00
}
public void OnDrag(PointerEventData eventData)
{
var delta = (Vector3)GetLocalDelta(eventData.delta);
switch (m_Target)
{
case Target.Self:
2023-08-17 08:43:02 +08:00
_rectTransform.localPosition += delta;
2022-06-09 00:50:36 +08:00
break;
case Target.Parent:
2023-08-17 08:43:02 +08:00
_rectTransform.parent.localPosition += delta;
2022-06-09 00:50:36 +08:00
break;
case Target.Custom:
2023-08-17 08:43:02 +08:00
_rectTransform.localPosition += delta;
2022-06-09 00:50:36 +08:00
if (m_CustomTarget)
{
2023-08-17 08:43:02 +08:00
if (m_UseCanvasScale)
{
delta.Scale(_canvas.rootCanvas.transform.localScale);
}
2022-06-09 00:50:36 +08:00
m_CustomTarget.localPosition += delta;
}
2023-08-17 08:43:02 +08:00
2022-06-09 00:50:36 +08:00
break;
}
}
public void OnEndDrag(PointerEventData eventData)
{
}
private Vector2 GetLocalDelta(Vector2 evDelta)
{
2023-08-17 08:43:02 +08:00
switch (_canvas.renderMode)
2022-06-09 00:50:36 +08:00
{
case RenderMode.ScreenSpaceOverlay:
2023-08-17 08:43:02 +08:00
{
var zero = transform.InverseTransformPoint(Vector2.zero);
var delta = transform.InverseTransformPoint(evDelta);
return delta - zero;
}
2022-06-09 00:50:36 +08:00
case RenderMode.ScreenSpaceCamera:
case RenderMode.WorldSpace:
2023-08-17 08:43:02 +08:00
{
RectTransformUtility.ScreenPointToLocalPointInRectangle(_rectTransform, Vector2.zero,
_canvas.worldCamera, out var zero);
RectTransformUtility.ScreenPointToLocalPointInRectangle(_rectTransform, evDelta,
_canvas.worldCamera, out var delta);
return delta - zero;
}
2022-06-09 00:50:36 +08:00
default:
2023-08-17 08:43:02 +08:00
throw new NotSupportedException();
2022-06-09 00:50:36 +08:00
}
}
2023-08-17 08:43:02 +08:00
private enum Target
{
Self,
Parent,
Custom
}
}