在本文,你將學(xué)會如何使用一句話代碼實(shí)現(xiàn)UGUI圖片的拖動,不需要坐標(biāo)的轉(zhuǎn)換,不需要Piovt的變換
效果演示:

效果演示
Tips: Showinfo腳本僅僅是為了看到筆者鼠標(biāo)是否進(jìn)行著觸發(fā)而添加的,別無它用
代碼:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class movePic : MonoBehaviour,IDragHandler ,IPointerDownHandler{
private RawImage img;
Vector3 offsetPos; //存儲按下鼠標(biāo)時的圖片-鼠標(biāo)位置差
void Start()
{
img = GetComponent<RawImage>();//獲取圖片,因?yàn)槲覀円@取他的RectTransform
}
public void OnDrag(PointerEventData eventData)
{
//將鼠標(biāo)的位置坐標(biāo)進(jìn)行鉗制,然后加上位置差再賦值給圖片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坐標(biāo)轉(zhuǎn)換,不考慮Piovt;
- 需要
using UnityEngine.EventSystem - 繼承2個接口
IDragHandler、IPointerDownHandler,在接口的實(shí)現(xiàn)中加入圖片移動邏輯
簡單拓展

可以作為輸入框背景,輸入框既美觀又實(shí)用
特別關(guān)注
上述代碼實(shí)現(xiàn)的前提是:Canvas -RenderMode-ScreenSpace_Overlay
如果要實(shí)現(xiàn):Canvas -RenderMode-Word Space下的圖片拖拽,涉及到坐標(biāo)裝換,也是挺簡單:
using System;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MoveImage : MonoBehaviour, IDragHandler, IPointerDownHandler
{
private Image img;
Vector3 offsetPos; //存儲按下鼠標(biāo)時的圖片-鼠標(biāo)位置差
Vector3 arragedPos; //保存經(jīng)過整理后的向量,用于圖片移動
void Start()
{
img = GetComponent<Image>();//獲取圖片,因?yàn)槲覀円@取他的RectTransform
}
public void OnDrag(PointerEventData eventData)
{
//將鼠標(biāo)的位置坐標(biāo)進(jìn)行鉗制,然后加上位置差再賦值給圖片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
其他實(shí)現(xiàn)方式:UGUI研究院之獲取UI子節(jié)點(diǎn)在Canvas的2D坐標(biāo)(十二)
標(biāo)簽:Unity3d 、UGUI 、IDragHandler、IPointerDownHandler、圖片拖拽、RectTransformUtility.ScreenPointToLocalPointInRectangle