UI事件之Drag拖拽事件
========================================================
2.UGUI 事件命名空間
當我們需要使用 UGUI 中的事件的時候,需要在腳本內引入專有命名空間:
using UnityEngine.EventSystems;
----------------------------------
2.拖拽相關事件接口
----------------------------------
1.三個拖拽事件相關接口
* IBeginDragHandler: 開始拖拽事件處理器;開始拖拽的一瞬間觸發。
* IDragHandler: 拖拽中事件處理器;拖拽過程中持續觸發。
* IEndDragHandler: 結束拖拽事件處理器;拖拽結束的一瞬間觸發。
----------------------------------
擴展理解:
這種“開始”“持續中”“結束”的模式,在 Unity 的交互中是非常常見的。
我們之前的碰撞檢測,觸發檢測,鼠標和鍵盤的按鍵檢測,都有這三個狀態。
----------------------------------
2.接口使用步驟
①當前腳本首先需要引入事件命名空間 EventSystems;
②在當前類繼承的父類的后方,用逗號分隔,寫需要使用到接口名;
③鼠標放到接口名上,右鍵-->實現接口-->實現接口 / 顯示實現接口;
④編寫相應事件的方法體,先簡單輸出調試。
----------------------------------
3.通過拖拽事件改變圖片位置
RectTransformUtility. / /RectTransform 工具類;
ScreenPointToWorldPointInRectangle( //屏幕坐標點轉化為世界坐標點;
m_RectTransform, //游戲物體的 RectTransform ;
eventData.position, //當前坐標位置點;
eventData.enterEventCamera, //事件攝像機;
out pos); //最終計算得到的世界坐標位置;
PointerEventData:指針事件數據。
上面的這個方法我們只需要寫在“拖拽中事件”方法內,將最終的 pos 位置值
持續賦值給當前游戲物體的 position 即可,就可以實現拖拽改變圖片的位置。
========================================================
實例: 鼠標拖動游戲物體
//獲取組件引用
m_RT = gameObject.GetComponent<RectTransform>();
//得到實時坐標位置轉化成3D坐標,並返回一個位置變量
RectTransformUtility.ScreenPointToWorldPointInRectangle(m_RT,eventData.position,eventData.enterEventCamera,out pos);
//賦值給游戲物體
m_RT.position = pos;
----------------------------------
總結: 繼承接口,實現接口,寫入處理代碼實現效果。
把下面的代碼保存到一個代碼文件,拖給一個游戲物體
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class ItemDrag : MonoBehaviour ,IBeginDragHandler,IDragHandler,IEndDragHandler { private RectTransform m_RT; void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) { print("IBeginDragHandler.OnBeginDrag"); gameObject.GetComponent<Transform>().position = Input.mousePosition; print("這是實現的拖拽開始接口"); } void IDragHandler.OnDrag(PointerEventData eventData) { print("IDragHandler.OnDrag"); //雖然用Input.mousePosition可以得到一個2D坐標,不過我們現在需要的是3D坐標,看下面 //gameObject.GetComponent<Transform>().position = Input.mousePosition; //3D坐標獲取方法 Vector3 pos; m_RT = gameObject.GetComponent<RectTransform>(); //屏幕坐標到世界坐標 RectTransformUtility.ScreenPointToWorldPointInRectangle(m_RT,eventData.position,eventData.enterEventCamera,out pos); m_RT.position = pos; print("拖拽中……"); } void IEndDragHandler.OnEndDrag(PointerEventData eventData) { print("IEndDragHandler.OnEndDrag"); gameObject.GetComponent<Transform>().position = Input.mousePosition; print("實現的拖拽結束接口"); } }
如有錯誤,歡迎指出。