using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
// UGUI拖动图片,脚本挂在Image上即可
public class TuoDongWuPin : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
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 = offPos + Input.mousePosition;
}
}