using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using System;
public class MouseDrag : MonoBehaviour, IPointerDownHandler,
IDragHandler, IPointerUpHandler, IEndDragHandler,
IPointerEnterHandler, IPointerExitHandler
{
RectTransform canvas;//得到Canvase的ui坐标
RectTransform TureRect;//得到图片的Ui坐标
Vector2
offset = new Vector2();//得到鼠标坐标和图片位置的差值
bool
bcontrol_Drag = false;
private
GameObject oldSlot;
private
Transform DragParent;//拖拽时用到的父对象
Vector3
imgScale = new Vector3(0.8f, 0.8f, 1);//图片缩放
Vector3
imgNormalScle = new Vector3(1, 1, 1);//正常大小
RectTransform ImgRect;//得到图片的Ui坐标
void
Awake()
{
canvas = GameObject.Find("Canvas").GetComponent();
DragParent = GameObject.Find("DragParent").transform;
}
void
Start()
{
TureRect = GetComponent();
ImgRect = DragParent.GetComponent();
}
///
///
当鼠标按下时
///
///
public void
OnPointerDown(PointerEventData eventData)
{
Vector2 mouseDown = eventData.position;//鼠标按下时屏幕的坐标
Vector2 GetUiPos = new Vector2();//返回Ui的坐标
bool isRect =
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,
mouseDown, eventData.enterEventCamera, out GetUiPos);
oldSlot = transform.parent.gameObject;
Debug.Log("oldSlot=" + oldSlot.name);
if (isRect)
{
offset = TureRect.anchoredPosition - GetUiPos;
ImgRect.anchoredPosition = GetUiPos;
// DragParent.anchoredPosition = offset;
}
}
///
/// 当鼠标拖动时调用
对应接口IDragHandler
///
///
public void
OnDrag(PointerEventData eventData)
{
ImgRect.SetAsFirstSibling();
// transform.SetParent(DragParent);
Vector2 mouseDrag = eventData.position;//当鼠标拖动时的屏幕坐标
Vector2 GetUiPosDrg = new Vector2();//存储转化后的坐标
bool isRect =
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas,
mouseDrag, eventData.enterEventCamera, out GetUiPosDrg);
if (isRect)
{
// TureRect.anchoredPosition =
offset + GetUiPosDrg;
}
}
///
/// 当鼠标抬起时调用
对应接口IPointUpHander
///
///
public void
OnPointerUp(PointerEventData eventData)
{
//
Debug.Log(eventData.pointerCurrentRaycast.gameObject.name);
// offset = Vector2.zero;
}
///
///
当鼠标结束拖动时调用 对应接口IEndDragHandler
///
///
public void
OnEndDrag(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
{