應用方法:將下面腳本掛載在需要拖拽功能的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 }