首页 > 编程语言 > 详细

unityUI拖拽

时间:2020-05-29 17:07:44      阅读:30      评论:0      收藏:0      [点我收藏+]
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拖拽

原文:https://www.cnblogs.com/tilyougogannbare666/p/12987758.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!