参考博客园“魔卡先生”博文
https://www.cnblogs.com/mrmocha/p/8040649.html
自己消化后,又做了详细备注
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class UIDragByMoCha : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public bool isPrecision;//是否精准拖拽
private Vector3 offset;//图片中心点 与 鼠标点 的偏移量(鼠标点在图片上时)
private RectTransform rectTransform;//图片的RectTransform组件
void Start()
{
//初始化
rectTransform= gameObject.GetComponent<RectTransform>();
}
//开始拖拽
public void OnBeginDrag(PointerEventData eventData)
{
//如果精确拖拽,则进行计算偏移量操作
if (isPrecision)
{
Vector3 originMouseWorldPos;//定义开始点击图片时,鼠标的世界坐标(下个语句就把屏幕坐标转换为世界坐标,赋值给它)
RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out originMouseWorldPos);
offset = transform.position - originMouseWorldPos;//计算偏移量
}
//否则,默认偏移量为0(默认情况下,鼠标一拖图片,图片中心点就会跑到鼠标位置,所以默认偏移量是0,即Vector3.zero)
else
{
offset = Vector3.zero;
}
//单独写的“设置被拖拽图片位置”方法 (写在了本页代码最后,接下来两个方法还会用到它,来设置图片位置)
SetDraggedPosition(eventData);
}
//拖拽中
public void OnDrag(PointerEventData eventData)
{
SetDraggedPosition(eventData);
}
//结束拖拽
public void OnEndDrag(PointerEventData eventData)
{
SetDraggedPosition(eventData);
}
/// <summary>
/// 设置被拖拽图片位置方法
/// </summary>
/// <param name="eventData"></param>
private void SetDraggedPosition(PointerEventData eventData)
{
//存储当前鼠标所在位置
Vector3 currentMousePos;
//UI屏幕坐标转换为世界坐标
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out currentMousePos))
{
//设置位置及偏移量
rectTransform.position = currentMousePos + offset;
}
}
}
注意:必须继承MonoBehaviour类,和IBeginDragHandler, IDragHandler, IEndDragHandler三个接口,而且
MonoBehaviour类,得写到开头,如下
勿忘引用命名空间using UnityEngine.EventSystems;
勾选此处是“精确拖拽”,否则是图片中心点跟着鼠标走的拖拽