关于Unity中UGUI 图片实现拖拽功能

应用方法:将下面脚本挂载在需要拖拽功能的UI图片上即可

两种拖拽选择:A.中心拖拽(图片中心跟随鼠标位置)m_isPrecision为false;

       B.精准拖拽(图片被鼠标点击的位置跟随鼠标位置)m_isPrecision为true;

 1 /*************************************************
 2  * 项目名称:UGUI通用
 3  * 脚本创建人:魔卡
 4  * 脚本创建时间:2017.12.14
 5  * 脚本功能:UI图片拖拽功能(将脚本挂载在需要拖放的图片上)
 6  * ***********************************************/
 7 using UnityEngine;
 8 using System.Collections;
 9 using UnityEngine.EventSystems;
10 
11 //UI图片拖拽功能类
12 public class UIDragByMocha : MonoBehaviour,IBeginDragHandler, IDragHandler, IEndDragHandler
13 {
14     [Header( "是否精准拖拽")]
15     public bool m_isPrecision;
16 
17     //存储图片中心点与鼠标点击点的偏移量
18     private Vector3 m_offset;
19 
20     //存储当前拖拽图片的RectTransform组件
21     private RectTransform m_rt;
22     void Start()
23     {
24         //初始化
25         m_rt= gameObject.GetComponent<RectTransform>();
26     }
27 
28     //开始拖拽触发
29     public void OnBeginDrag(PointerEventData eventData)
30     {
31         //如果精确拖拽则进行计算偏移量操作
32         if (m_isPrecision)
33         {
34             // 存储点击时的鼠标坐标
35             Vector3 tWorldPos;
36             //UI屏幕坐标转换为世界坐标
37             RectTransformUtility.ScreenPointToWorldPointInRectangle(m_rt, eventData.position, eventData.pressEventCamera, out tWorldPos);
38             //计算偏移量   
39             m_offset = transform.position - tWorldPos;
40         }
41             //否则,默认偏移量为0
42         else
43         {
44             m_offset = Vector3.zero;
45         }
46 
47         SetDraggedPosition(eventData);
48     }
49 
50     //拖拽过程中触发
51     public void OnDrag(PointerEventData eventData)
52     {
53         SetDraggedPosition(eventData);
54     }
55 
56     //结束拖拽触发
57     public void OnEndDrag(PointerEventData eventData)
58     {
59         SetDraggedPosition(eventData);
60     }
61 
62     /// <summary>
63     /// 设置图片位置方法
64     /// </summary>
65     /// <param name="eventData"></param>
66     private void SetDraggedPosition(PointerEventData eventData)
67     {
68         //存储当前鼠标所在位置
69         Vector3 globalMousePos;
70         //UI屏幕坐标转换为世界坐标
71         if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
72         {
73             //设置位置及偏移量
74             m_rt.position = globalMousePos + m_offset;
75         }
76     }
77 }
原文地址:https://www.cnblogs.com/mrmocha/p/8040649.html