1 using UnityEngine; 2 using UnityEngine.EventSystems; 3 using UnityEngine.UI; 4
5 public class LoginMoveWithMouse : MonoBehaviour, IDragHandler, IPointerDownHandler { 6 //偏移值
7 private Vector3 offset; 8 //父物體變換組件
9 private RectTransform PrentRTF; 10
11 private void Start() { 12 //查找父物體變換組件,僅需要執行一次即可,所以寫在Start()方法
13 PrentRTF = this.transform.parent as RectTransform; 14 } 15
16
17 //拖拽時執行方法
18 public void OnDrag(PointerEventData eventData) { 19
20 /*
21 僅限於Canvas overlay渲染模式模式,鼠標拖動圖片移動 22 如果考慮偏移量問題,可以直接寫下邊的代碼.簡單 23 this.transform.position = eventData.position; 24 */
25
26
27 /*
28 通用模式 29 將屏幕坐標轉換為世界坐標 30 RectTransformUtility.ScreenPointToWorldPointInRectangle 31 (父物體的變換組件,屏幕坐標,攝像機,out 世界坐標) 32 */
33 Vector3 wordPoint; 34 RectTransformUtility.ScreenPointToWorldPointInRectangle(PrentRTF, eventData.position, eventData.pressEventCamera, out wordPoint); 35 /*移動,並計算偏移量*/
36 this.transform.position = wordPoint + offset; 37
38
39
40
41 } 42
43 /// <summary>
44 /// 當光標按下物體時執行,此方法用於記錄偏移值 45 /// </summary>
46 /// <param name="eventData">獲取到的信息</param>
47 public void OnPointerDown(PointerEventData eventData) { 48 /*通用模式,鼠標拖動圖片移動 49 將屏幕坐標轉換為世界坐標 50 //RectTransformUtility.ScreenPointToWorldPointInRectangle(父物體的變換組件,屏幕坐標,攝像機,out 世界坐標) 51 */
52 Vector3 wordPoint; 53 RectTransformUtility.ScreenPointToWorldPointInRectangle(PrentRTF, eventData.position, eventData.pressEventCamera, out wordPoint); 54 //記錄偏移值(圖片的軸心點 - 鼠標點下的位置)
55 offset = this.transform.position - wordPoint; 56 } 57 }
第二種方法:將代碼掛在到需要移動的對象身上
1 using UnityEngine; 2 using UnityEngine.EventSystems; 3 4 public class MoveBag : MonoBehaviour,IDragHandler 5 { 6 RectTransform currentRect; 7 8 private void Awake() { 9 currentRect = GetComponent<RectTransform>(); 10 } 11 12 /// <summary> 13 /// 當拖拽時觸發 14 /// </summary> 15 /// <param name="eventData"></param> 16 public void OnDrag(PointerEventData ed) { 17 //中心錨點位置 += 鼠標的移動 18 currentRect.anchoredPosition += ed.delta; 19 } 20 }
附GIF圖,注意鼠標點擊的位置,只要是點擊在圖片上,
任意位置都能移動且計算並修復偏移值
如不想考慮偏移值,請看23行代碼