[Unity3D] 鼠标点击图片移动效果

 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行代码

时间若流水,恍惚间逝去
原文地址:https://www.cnblogs.com/alanshreck/p/13582259.html