拖拽實現
拖拽事件實現:
? ? ? ? 半透明漸變貼圖在ios設備下,使用壓縮會造成圖片質量損失,所以可以將半透明漸變UI切片單獨制作真彩色圖集
拖拽事件組
? ? ? ? IBeginDragHandler:檢測到射線后,當拖拽動作開始時執行一次回調函數
? ? ? ? IDragHandler:拖拽開始后,有拖拽位置變化時,執行回調函數(每個移動)
? ? ? ? IEndDragHandler:拖拽進行中時,當鼠標或手抬起時,執行一次回調函數
public class TestDrag : MonoBehaviour,
IBeginDragHandler,IEndDragHandler,
IDragHandler
{public void OnBeginDrag(PointerEventData eventData){Debug.Log("開始拖拽");}void IEndDragHandler.OnEndDrag(PointerEventData eventData){Debug.Log("結束拖拽");}//PointerEventData是Unity從設備硬件接收到的數據和事件相關的一些數據//拖拽中會連續回調,將被拖拽物體的執行代碼放在OnDrag中才能實現物體的連續移動public void OnDrag(PointerEventData eventData){//拖拽移動的實現//手指觸摸屏幕,產生坐標點//移動實現,需要將屏幕的坐標點,轉換為被移動物體的本地坐標系下的位置點//使用被移動物體的transform,通過本地坐標系的點實現位置改變//相對的父物體是誰?//屏幕的坐標點//攝像機是誰?Vector2 localPos;RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent as RectTransform,//參考坐標系對象的RectTransformeventData.position,//事件發生時屏幕的觸摸點eventData.pressEventCamera,//觸發事件的相機out localPos//以第一個參數作為參考坐標系的事件觸發位置);transform.localPosition=localPos;Debug.Log("拖拽中......");}
}
如何獲取物體的位置:
? ? ? ? 位置:相對量,需要有參照物體
? ? ? ? 屏幕坐標:手點擊屏幕時生成
? ? ? ? DragArea本地坐標:控制搖桿(DragBar)的位置?
如何通過屏幕坐標系下的點,轉換到DragArea本地坐標系下的點
//通過屏幕事件坐標,獲得本地事件坐標
RectTransformUtility.ScreenPointToLocalPointInRectangle(transform as RectTransform,//參考坐標系對象的RectTransformeventData.position,//事件發生時屏幕的觸摸點eventData.pressEventCamera,//觸發事件的相機out localPos//以第一個參數作為參考坐標系的事件觸發位置
);
搖桿實現
相關代碼如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;//需要在UI上設定一個點擊區域,點擊后,搖桿出現,抬起后搖桿消失
//根據點擊位置移動整個搖桿
//拖拽時將桿的位置進行移動
//限制搖桿距離
public class DragController : MonoBehaviour,IPointerDownHandler,IPointerUpHandler,IDragHandler
{public GameObject dragBar;public Transform bar;//可移動區域的最遠距離public float R;// Start is called before the first frame updatevoid Start(){dragBar.SetActive(false);}public void OnPointerDown(PointerEventData eventData){dragBar.SetActive(true);Vector2 localPos;RectTransformUtility.ScreenPointToLocalPointInRectangle(transform as RectTransform,//參考坐標系對象的RectTransformeventData.position,//事件發生時屏幕的觸摸點eventData.pressEventCamera,//觸發事件的相機out localPos//以第一個參數作為參考坐標系的事件觸發位置);dragBar.transform.localPosition = localPos;}public void OnPointerUp(PointerEventData eventData){dragBar.SetActive(false);bar.localPosition = Vector3.zero;}public void OnDrag(PointerEventData eventData){Vector2 localPos;RectTransformUtility.ScreenPointToLocalPointInRectangle(dragBar.transform as RectTransform,//參考坐標系對象的RectTransformeventData.position,//事件發生時屏幕的觸摸點eventData.pressEventCamera,//觸發事件的相機out localPos//以第一個參數作為參考坐標系的事件觸發位置);//判斷當前向量的長度是否大于Rif (localPos.magnitude > R){localPos = localPos.normalized * R;}bar.transform.localPosition = localPos;}
}
Unity中的具體操作如圖:
運行時如圖:
?
該系列專欄為網課課程筆記,僅用于學習參考。?