UGUI拖动界面

主要 依赖于几个接口 ,代码直接贴出来了
public class DragUI : MonoBehaviour, IPointerDownHandler, IDragHandler, IEndDragHandler
{

    // 鼠标起点  
    private Vector2 originalLocalPointerPosition;
    // 面板起点  
    private Vector3 originalPanelLocalPosition;
    // 当前面板  
    private RectTransform curPanelRect;
    // 父物体  
    private RectTransform parentRect;
    // private static int siblingIndex = 0;
    private void Awake()
    {
        curPanelRect = transform.parent as RectTransform;
        parentRect = transform.parent.parent as RectTransform;
    }

    /// <summary>
    ///  鼠标按下  
    /// </summary>
    /// <param name="data"></param>
    public void OnPointerDown(PointerEventData data)
    {
        curPanelRect.transform.SetAsLastSibling();
        // 当前面板起点  
        originalPanelLocalPosition = curPanelRect.localPosition;
        // 通过屏幕中的鼠标点,获取在父物体中的鼠标点  
        RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRect, data.position,
            data.pressEventCamera, out originalLocalPointerPosition);
    }
    /// <summary>
    /// 拖拽
    /// </summary>
    /// <param name="data"></param>  
    public void OnDrag(PointerEventData data)
    {
        if (curPanelRect == null || parentRect == null)
            return;
        //虚化界面      
        transform.parent.GetComponent<CanvasGroup>().alpha = 0.5f;
        Vector2 localPointerPosition;
        // 本地鼠标位置  
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(parentRect, data.position, data.pressEventCamera, out localPointerPosition))
        {
            Vector3 offsetToOriginal = localPointerPosition - originalLocalPointerPosition;
            curPanelRect.localPosition = originalPanelLocalPosition + offsetToOriginal;
        }
        ClampToWindow();
    }

    /// <summary>
    ///  限制当前面板在父物体中的位置  
    /// </summary>
    private void ClampToWindow()
    {
        // 面板位置  
        Vector3 pos = curPanelRect.localPosition;
        //可移动的最小距离和最大距离
        Vector3 minPosition = parentRect.rect.min - curPanelRect.rect.min;
        Vector3 maxPosition = parentRect.rect.max - curPanelRect.rect.max;
        pos.x = Mathf.Clamp(curPanelRect.localPosition.x, minPosition.x, maxPosition.x);
        pos.y = Mathf.Clamp(curPanelRect.localPosition.y, minPosition.y, maxPosition.y);
        curPanelRect.localPosition = pos;
    }

    public void OnEndDrag(PointerEventData eventData)
    {

        transform.parent.GetComponent<CanvasGroup>().alpha = 1f;

    }
}

}
需要被拖动 的UI面板添加这个脚本就好了

猜你喜欢

转载自blog.csdn.net/weixin_42430280/article/details/108871775