首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >UGUI拖动界面

UGUI拖动界面

作者头像
用户12298955
发布2026-05-06 16:43:45
发布2026-05-06 16:43:45
860
举报

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

代码语言:javascript
复制
    // 鼠标起点  
    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面板添加这个脚本就好了

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2026-05-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档