Unity UGUI实现鼠标拖动图片

时间:2023-03-08 17:22:29

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
/// <summary>
/// **************************UGUI拖动图片,脚本挂在Image上即可*********************************
/// </summary>
public class TuoDongWuPin : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
//需要被实例化的与制体
//public GameObject YuSheWu;
//实例化后的对象
private Image img;
Vector3 offPos;//存储按下鼠标时的图片-鼠标位置差
Vector3 arragedPos; //保存经过整理后的向量,用于图片移动
/// <summary>
/// 开始拖拽的时候
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(transform.GetComponent<RectTransform>(), Input.mousePosition
, eventData.enterEventCamera, out arragedPos))
{
offPos = transform.position - arragedPos;
}
}
/// <summary>
/// 拖拽中
/// </summary>
/// <param name="eventData"></param>
public void OnDrag(PointerEventData eventData)
{
transform.position = offPos + Input.mousePosition;
}
/// <summary>
/// 拖拽结束
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
transform.position = transform.parent.transform.position;
}
}