UGUI—Drag与Drop

作者:追风剑情 发布于:2019-10-21 15:56 分类:Unity3d

示例:拖拽Icon

工程截图

1111.png

2222.png

UIDragItem.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;

[DisallowMultipleComponent]
public class UIDragItem : UIBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler, IDropHandler
{
    private RectTransform m_RectTransform;
    private RectTransform m_ParentTransform;
    private Graphic m_Graphic;
    private Vector2 localPoint = Vector2.zero;
    private Vector2 parentPoint = Vector2.zero;

    protected override void Awake()
    {
        base.Awake();
        m_RectTransform = this.GetComponent<RectTransform>();
        m_ParentTransform = (RectTransform)m_RectTransform.parent;
        m_Graphic = this.GetComponent<Graphic>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        Vector2 screenPoint = eventData.pressPosition;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(m_RectTransform, screenPoint, null, out localPoint);
        UpdatePosition();

        if (m_Graphic != null)
            m_Graphic.raycastTarget = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector2 screenPoint = eventData.position;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(m_ParentTransform, screenPoint, null, out parentPoint);
        UpdatePosition();
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (m_Graphic != null)
            m_Graphic.raycastTarget = true;
    }

    //OnDrop在OnEndDrag之前触发
    public void OnDrop(PointerEventData eventData)
    {
        //Debug.Log("OnDrop: " + gameObject.name);
    }

    private void UpdatePosition()
    {
        anchoredPosition = parentPoint - localPoint;
    }

    private Vector2 anchoredPosition
    {
        get { return m_RectTransform.anchoredPosition; }
        set { m_RectTransform.anchoredPosition = value; }
    }
}

UIDropItem.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;

[DisallowMultipleComponent]
public class UIDropItem : UIBehaviour, IDropHandler
{
    public void OnDrop(PointerEventData eventData)
    {
        Debug.Log("OnDrop: " + gameObject.name);

        GameObject pointerDrag = eventData.pointerDrag;
        if (pointerDrag == null)
            return;
        Image dragImage = pointerDrag.GetComponent<Image>();
        this.GetComponent<Image>().sprite = dragImage.sprite;
    }
}

运行测试

5555.gif

标签: Unity3d

Powered by emlog  蜀ICP备18021003号   sitemap

川公网安备 51019002001593号