Unity UGUI实现拖拽Tag吸附

功能简述:实现UI标签拖拽到目标Blank,一定范围内实现自动吸附,否则回到原位。

实现思路:利用IBeginDragHandler, IDragHandler, IEndDragHandler完成逻辑。

动图效果:

代码:

/*************************************************
 * 脚本功能:UI选项拖拽功能(脚本挂在每个选项上)
 * 作者:CN
 * ***********************************************/
using UnityEngine;
using UnityEngine.EventSystems;

public class UIOptionDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    [Header("目标位置")]
    public Transform[] TargetLocations;

    //存储当前拖拽图片的RectTransform组件
    private RectTransform m_rt;
    private Vector3 m_originPos;
    //存储图片中心点与鼠标点击点的偏移量
    private Vector3 m_offset;
    //当前是否吸附
    private bool isAdsorbed = false;

    void Start()
    {
        m_rt = transform.GetComponent<RectTransform>();
        m_originPos = m_rt.position;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Left)
        {
            // 存储点击时的鼠标坐标
            Vector3 tWorldPos;
            //UI屏幕坐标转换为世界坐标
            RectTransformUtility.ScreenPointToWorldPointInRectangle(m_rt, eventData.position, eventData.pressEventCamera, out tWorldPos);
            //计算偏移量   
            m_offset = transform.position - tWorldPos;
        }
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (eventData.button == PointerEventData.InputButton.Left)
            m_rt.position = Input.mousePosition + m_offset;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (!isAdsorbed)
        {
            m_rt.position = m_originPos;
        }
    }

    void Update()
    {
        for (int i = 0; i < TargetLocations.Length; i++)
        {
            if (Mathf.Sqrt((m_rt.position - TargetLocations[i].position).magnitude) < 5)
            {
                m_rt.position = TargetLocations[i].position;
                isAdsorbed = true;
                break;
            }
            else
                isAdsorbed = false;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值