參考鏈接:https://www.cnblogs.com/mrmocha/p/8040649.html;
/*************************************************
* 項(xiàng)目名稱(chēng):UGUI通用
* 腳本創(chuàng)建人:魔卡
* 腳本創(chuàng)建時(shí)間:2017.12.14
* 腳本功能:UI圖片拖拽功能(將腳本掛載在需要拖放的圖片上)
* ***********************************************/
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
//UI圖片拖拽功能類(lèi)
public class UIDragByMocha : MonoBehaviour,IBeginDragHandler, IDragHandler, IEndDragHandler
{
? ? [Header( "是否精準(zhǔn)拖拽")]
? ? public bool m_isPrecision;
? ? //存儲(chǔ)圖片中心點(diǎn)與鼠標(biāo)點(diǎn)擊點(diǎn)的偏移量
? ? private Vector3 m_offset;
? ? //存儲(chǔ)當(dāng)前拖拽圖片的RectTransform組件
? ? private RectTransform m_rt;
? ? void Start()
? ? {
? ? ? ? //初始化
? ? ? ? m_rt= gameObject.GetComponent<RectTransform>();
? ? }
? ? //開(kāi)始拖拽觸發(fā)
? ? public void OnBeginDrag(PointerEventData eventData)
? ? {
? ? ? ? //如果精確拖拽則進(jìn)行計(jì)算偏移量操作
? ? ? ? if (m_isPrecision)
? ? ? ? {
? ? ? ? ? ? // 存儲(chǔ)點(diǎn)擊時(shí)的鼠標(biāo)坐標(biāo)
? ? ? ? ? ? Vector3 tWorldPos;
? ? ? ? ? ? //UI屏幕坐標(biāo)轉(zhuǎn)換為世界坐標(biāo)
? ? ? ? ? ? RectTransformUtility.ScreenPointToWorldPointInRectangle(m_rt, eventData.position, eventData.pressEventCamera, out tWorldPos);
? ? ? ? ? ? //計(jì)算偏移量?
? ? ? ? ? ? m_offset = transform.position - tWorldPos;
? ? ? ? }
? ? ? ? ? ? //否則,默認(rèn)偏移量為0
? ? ? ? else
? ? ? ? {
? ? ? ? ? ? m_offset = Vector3.zero;
? ? ? ? }
? ? ? ? SetDraggedPosition(eventData);
? ? }
? ? //拖拽過(guò)程中觸發(fā)
? ? public void OnDrag(PointerEventData eventData)
? ? {
? ? ? ? SetDraggedPosition(eventData);
? ? }
? ? //結(jié)束拖拽觸發(fā)
? ? public void OnEndDrag(PointerEventData eventData)
? ? {
? ? ? ? SetDraggedPosition(eventData);
? ? }
? ? /// <summary>
? ? /// 設(shè)置圖片位置方法
? ? /// </summary>
? ? /// <param name="eventData"></param>
? ? private void SetDraggedPosition(PointerEventData eventData)
? ? {
? ? ? ? //存儲(chǔ)當(dāng)前鼠標(biāo)所在位置
? ? ? ? Vector3 globalMousePos;
? ? ? ? //UI屏幕坐標(biāo)轉(zhuǎn)換為世界坐標(biāo)
? ? ? ? if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
? ? ? ? {
? ? ? ? ? ? //設(shè)置位置及偏移量
? ? ? ? ? ? m_rt.position = globalMousePos + m_offset;
? ? ? ? }
? ? }
}