Unity3D 通用拖拽

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

public class DialogDrag : MonoBehaviour,IDragHandler,IPointerDownHandler
{
    private RectTransform parentRTF;

    private Vector3 offset;

    public void OnPointerDown(PointerEventData eventData)
    {
        //记录从按下点到中心点偏移量(坐标)
        //屏幕坐标-->世界坐标
        RectTransformUtility.ScreenPointToWorldPointInRectangle(parentRTF, eventData.position, eventData.pressEventCamera, out Vector3 worldPoint);
        offset = this.transform.position - worldPoint;
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 worldPoint;
        //屏幕坐标-->世界坐标
        RectTransformUtility.ScreenPointToWorldPointInRectangle(parentRTF, eventData.position, eventData.pressEventCamera, out worldPoint);
        //根据偏移量移动当前UI
        this.transform.position = worldPoint + offset;
    }

   
    void Start()
    {
        parentRTF = this.transform.parent as RectTransform;
    }
}

 

posted @ 2019-07-05 10:54  cct7860  阅读(222)  评论(0编辑  收藏  举报