UGUI拖动界面

该代码段展示了一个Unity脚本,实现了UI面板的拖放功能。当用户按下鼠标时记录初始位置,拖动时更新面板位置,并在拖放结束后恢复正常状态。此功能可用于创建交互式的UI元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要 依赖于几个接口 ,代码直接贴出来了
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面板添加这个脚本就好了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值