Unity3D 一句話代碼實(shí)現(xiàn)UGUI圖片的拖拽功能

在本文,你將學(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:

  1. 最簡代碼,不涉及到Rect坐標(biāo)轉(zhuǎn)換,不考慮Piovt;
  2. 需要using UnityEngine.EventSystem
  3. 繼承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.WorldToScreenPointCamera.main.ScreenToWorldPoint

其他實(shí)現(xiàn)方式:UGUI研究院之獲取UI子節(jié)點(diǎn)在Canvas的2D坐標(biāo)(十二)

標(biāo)簽:Unity3d 、UGUI 、IDragHandler、IPointerDownHandler、圖片拖拽、RectTransformUtility.ScreenPointToLocalPointInRectangle

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容