应用方法:将下面脚本挂载在需要拖拽功能的UI图片上即可
两种拖拽选择:A.中心拖拽(图片中心跟随鼠标位置)m_isPrecision为false;
B.精准拖拽(图片被鼠标点击的位置跟随鼠标位置)m_isPrecision为true;
常用的代码和主要实现方式都贴在下面了;
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using DG.Tweening;
//UI图片拖拽功能类
public class UIDragBySSW : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler,IPointerEnterHandler, IPointerExitHandler
{
public ModelCon MC;
[Header("是否精准拖拽")]
public bool m_isPrecision;
//存储图片中心点与鼠标点击点的偏移量
private Vector3 m_offset;
//存储当前拖拽图片的RectTransform组件
private RectTransform m_rt;
private Vector3 imgPos;
private Vector3 imgscale;
void Start()
{
//初始化
m_rt = gameObject.GetComponent<RectTransform>();
imgPos = m_rt.anchoredPosition3D;
imgscale = m_rt.localScale;
}
//开始拖拽触发
public void OnBeginDrag(PointerEventData eventData)
{
//如果精确拖拽则进行计算偏移量操作
if (m_isPrecision)
{
// 存储点击时的鼠标坐标
Vector3 tWorldPos;
//UI屏幕坐标转换为世界坐标
RectTransformUtility.ScreenPoi