[Unity3D] 如何实现鼠标点击拖拽图片移动图片跟随移动

时间:2020-09-09 19:16:57   收藏:0   阅读:130
 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 }

附GIF图,注意鼠标点击的位置,只要是点击在图片上,

任意位置都能移动且计算并修复偏移值

如不想考虑偏移值,请看23行代码

技术图片

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!