在本文,你将学会如何使用一句话代码实现UGUI图片的拖动,不需要坐标的转换,不需要Piovt的变换
效果演示:
Tips: Showinfo脚本仅仅是为了看到笔者鼠标是否进行着触发而添加的,别无它用
代码:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class movePic : MonoBehaviour,IDragHandler ,IPointerDownHandler{
private RawImage img;
Vector3 offsetPos; //存储按下鼠标时的图片-鼠标位置差
void Start()
{
img = GetComponent<RawImage>();//获取图片,因为我们要获取他的RectTransform
}
public void OnDrag(PointerEventData eventData)
{
//将鼠标的位置坐标进行钳制,然后加上位置差再赋值给图片position
img.rectTransform.position = new Vector3(Mathf.Clamp(Input.mousePosition.x, 0, Screen.width), Mathf.Clamp(Input.mousePosition.y, 0, Screen.height), 0) + offsetPos;
}
public void OnPointerDown(PointerEventData eventData)
{
offsetPos = img.rectTransform.position - Input.mousePosition;
}
}
Tips:
- 最简代码,不涉及到Rect坐标转换,不考虑Piovt;
- 需要
using UnityEngine.EventSystem
- 继承2个接口
IDragHandler
、IPointerDownHandler
,在接口的实现中加入图片移动逻辑
简单拓展
特别关注
上述代码实现的前提是:Canvas -RenderMode-ScreenSpace_Overlay
如果要实现:Canvas -RenderMode-Word Space下的图片拖拽,涉及到坐标装换,也是挺简单:
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MoveImage : MonoBehaviour, IDragHandler, IPointerDownHandler
{
private Image img;
Vector3 offsetPos; //存储按下鼠标时的图片-鼠标位置差
Vector3 arragedPos; //保存经过整理后的向量,用于图片移动
void Start()
{
img = GetComponent<Image>();//获取图片,因为我们要获取他的RectTransform
}
public void OnDrag(PointerEventData eventData)
{
//将鼠标的位置坐标进行钳制,然后加上位置差再赋值给图片position
img.transform.position =Camera.main.ScreenToWorldPoint(new Vector3(Mathf.Clamp(Input.mousePosition.x, 0, Screen.width), Mathf.Clamp(Input.mousePosition.y, 0, Screen.height), 0) + offsetPos);
}
public void OnPointerDown(PointerEventData eventData)
{
offsetPos = Camera.main.WorldToScreenPoint(img.rectTransform.position) - Input.mousePosition;
}
}
Tips:请注意我用到了:Camera.main.WorldToScreenPoint
和Camera.main.ScreenToWorldPoint
其他实现方式:UGUI研究院之获取UI子节点在Canvas的2D坐标(十二)
标签:Unity3d 、UGUI 、IDragHandler、IPointerDownHandler、图片拖拽、RectTransformUtility.ScreenPointToLocalPointInRectangle