UGUI 拖拽功能的实现

1.内容只要继承了IBeginDragHandlerIDragHandler、和IEndDragHandler这三个接口,并实现了OnBeginDragOnDragOnEndDrag这三个方法,我们就可以实现拖拽功能。其中,OnBeginDrag处理开始拖动时要做什么事,OnDrag处理拖动过程中要做什么事,OnEndDrag处理拖动结束时要做什么事

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

public class DragableCard : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    // begin dragging
    public void OnBeginDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    // during dragging
    public void OnDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    // end dragging
    public void OnEndDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    /// 
    /// set position of the dragged game object
    /// 
    /// 
    private void SetDraggedPosition(PointerEventData eventData)
    {
        var rt = gameObject.GetComponent();

        // transform the screen point to world point int rectangle
        Vector3 globalMousePos;
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            rt.position = globalMousePos;
        }
    }}

2.继承了IDropHandler, IPointerEnterHandler, IPointerExitHandler这三个接口,同样也实现对应的三个方法OnDropOnPointerEnterOnPointerExit。其中,OnDrop处理松开鼠标左键时要做什么事,OnPointerEnter处理鼠标指针进入挂载该脚本的物体区域时要做什么事,OnPointerExit处理处理鼠标指针移出挂载该脚本的物体区域时要做什么事

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

public class DropMe : MonoBehaviour, IDropHandler, IPointerEnterHandler, IPointerExitHandler
{
    public GameObject m_myCardsObj;

    private bool m_isIn = false;

    public void OnEnable()
    {
        Debug.Log("............");
    }

    // when you release the left button of mouse
    public void OnDrop(PointerEventData data)
    {
        Debug.Log(string.Format(">>>>> {0}", m_isIn));

        if (!m_isIn)
        {
            m_myCardsObj.GetComponent().UpdateShow();
        }
    }

    // when the mouse moving in the game object
    public void OnPointerEnter(PointerEventData data)
    {
        m_isIn = true;
        Debug.Log(m_isIn);
    }

    // when the mouse moving out the game object
    public void OnPointerExit(PointerEventData data)
    {
        m_isIn = false;
        Debug.Log(m_isIn);
    }

    private Sprite GetDropSprite(PointerEventData data)
    {
        var originalObj = data.pointerDrag;
        if (originalObj == null)
            return null;

        var srcImage = originalObj.GetComponent();
        if (srcImage == null)
            return null;

        return srcImage.sprite;
    }
}

你可能感兴趣的:(UGUI)