[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行代码
2022年11月23日更新方法
将以下代码挂载到需要拖动的对象上即可
using UnityEngine; using UnityEngine.EventSystems; public class DragGameObject : MonoBehaviour, IDragHandler { RectTransform currentRect; private void Awake() { currentRect = GetComponent<RectTransform>(); } public void OnDrag(PointerEventData eventData) { //将对象的中心锚点 +上 鼠标的移动 currentRect.anchoredPosition +=eventData.delta; } }
时间若流水,恍惚间逝去
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?