2025-06-25 13:45:30 +08:00

76 lines
2.0 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
/// <summary>
/// ͨÓÃÍÏ×§×é¼þ
/// </summary>
public class DragUIItem :MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler
{
private RectTransform rectTransform;
private Canvas canvas;
private Vector2 startPosition;
private bool restrictToCanvas = true;
private LayoutGroup parentLayoutGroup;
private void Awake()
{
rectTransform = GetComponent<RectTransform>();
canvas = GetComponentInParent<Canvas>();
startPosition = rectTransform.anchoredPosition;
parentLayoutGroup = GetComponentInParent<LayoutGroup>();
}
public void OnBeginDrag(PointerEventData eventData)
{
if (parentLayoutGroup != null)
parentLayoutGroup.enabled = false;
parentLayoutGroup.GetComponent<ContentSizeFitter>().enabled = false;
}
public void OnDrag(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(
rectTransform,
eventData.position,
canvas.worldCamera,
out Vector3 worldPosition))
{
rectTransform.position = worldPosition;
if (restrictToCanvas)
RestrictToCanvasBounds();
}
}
public void OnEndDrag(PointerEventData eventData)
{
parentLayoutGroup.enabled = true;
parentLayoutGroup.GetComponent<ContentSizeFitter>().enabled = true;
}
private void RestrictToCanvasBounds()
{
Vector3[] corners = new Vector3[4];
canvas.GetComponent<RectTransform>().GetWorldCorners(corners);
Vector3 min = corners[0];
Vector3 max = corners[2];
Vector3 pos = rectTransform.position;
pos.x = Mathf.Clamp(pos.x, min.x, max.x);
pos.y = Mathf.Clamp(pos.y, min.y, max.y);
rectTransform.position = pos;
}
public void ResetPosition()
{
rectTransform.anchoredPosition = startPosition;
}
}