unity UI限制拖拽范围

unity UI限制拖拽范围
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragUI : MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler
{
    private RectTransform rectTransform;
    //限制范围的UI
    public RectTransform container;

    Vector3 offset = Vector3.zero;
  
    // 最小、最大X、Y坐标
    float minX, maxX, minY, maxY;
    public void OnBeginDrag(PointerEventData eventData)
    {
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, eventData.position, eventData.enterEventCamera, out Vector3 globalMousePos))
        {
            // 计算偏移量
            offset = rectTransform.position - globalMousePos;
            // 设置拖拽范围
            SetDragRange();
        }
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 pos;
        RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, eventData.position, eventData.enterEventCamera, out Vector3 globalMousePos);
        pos = DragRangeLimit(globalMousePos + offset);
        rectTransform.position = new Vector3(pos.x, rectTransform.position.y, rectTransform.position.z);

    }

    public void OnEndDrag(PointerEventData eventData)
    {
     

    }

    // Start is called before the first frame update
    void Start()
    {
        rectTransform = GetComponent<RectTransform>();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    // 设置最大、最小坐标
    void SetDragRange()
    {
        // 最小x坐标 = 容器当前x坐标 - 容器轴心距离左边界的距离 + UI轴心距离左边界的距离
        minX = container.position.x
            - container.pivot.x * container.rect.width
            + rectTransform.rect.width * rectTransform.pivot.x;

        // 最大x坐标 = 容器当前x坐标 + 容器轴心距离右边界的距离 - UI轴心距离右边界的距离
        maxX = container.position.x
            + (1 - container.pivot.x) * container.rect.width
            - rectTransform.rect.width * (1 - rectTransform.pivot.x);

        // 最小y坐标 = 容器当前y坐标 - 容器轴心距离底边的距离 + UI轴心距离底边的距离
        minY = container.position.y
            - container.pivot.y * container.rect.height
            + rectTransform.rect.height * rectTransform.pivot.y;

        // 最大y坐标 = 容器当前x坐标 + 容器轴心距离顶边的距离 - UI轴心距离顶边的距离
        maxY = container.position.y
            + (1 - container.pivot.y) * container.rect.height
            - rectTransform.rect.height * (1 - rectTransform.pivot.y);
    }


    // 限制坐标范围
    Vector3 DragRangeLimit(Vector3 pos)
    {
        pos.x = Mathf.Clamp(pos.x, minX, maxX);
        pos.y = Mathf.Clamp(pos.y, minY, maxY);
        return pos;
    }

}

原文链接:https://blog.csdn.net/weixin\_38221585/article/details/99674143