unityUI拖拽

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DrawPanel : MonoBehaviour ,IDragHandler,IDropHandler
{
    private RectTransform rt;
    public RectTransform canvasRt;
    private Vector2 panlePosition;//鼠标在当前的位置
    public bool isFirst = true;//是否为第一次
    public void OnDrag(PointerEventData eventData)//在控件上拖拽时候回调
    {
        Vector2 mousePos = eventData.position;
        Vector2 uguiPos = new Vector2();
        //下面这行调用Utility工具把鼠标坐标转换成UI坐标,参数第一个是鼠标坐标转换到的物体,第二个是鼠标点,第三个是事件是由哪个摄像机执行的,第四个是输出本地(UI)坐标
      bool isInRect=  RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRt, mousePos,eventData.enterEventCamera,out uguiPos);//鼠标在全屏位置
        if (isInRect == true)
        {
            rt.anchoredPosition = uguiPos-panlePosition;//把转换后的坐标给我们的物体,两个二维向量相减,确定距离
        }
        if (isFirst)
        {
            isFirst = false;
            RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, mousePos, eventData.enterEventCamera, out panlePosition);//鼠标在当前坐标位置
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        rt = transform as RectTransform;//当前Transform组件转换成2维组件
    }
    // Update is called once per frame
    void Update()
    {
       
    }
    public void OnDrop(PointerEventData eventData)//停止拖拽
    {
        isFirst = true;//设为第一次
    }
}

你可能感兴趣的:(unityUI拖拽)