You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
4.1 KiB

using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
using System;
namespace Level23
{
//给空间添加监听事件要实现的一些接口
public class MyDrag : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler,
IEndDragHandler, IPointerEnterHandler, IPointerExitHandler
{
public RectTransform canvas; //得到canvas的ugui坐标
public Level23 lvRoot;
private RectTransform imgRect; //得到图片的ugui坐标
Vector2 offset = new Vector3(); //用来得到鼠标和图片的差值
Vector3 imgReduceScale = new Vector3(0.6f, 0.6f, 1); //设置图片缩放
Vector3 imgNormalScale = new Vector3(1, 1, 1); //正常大小
Vector3 selfV3 = Vector3.zero;
// Use this for initialization
void Start()
{
imgRect = GetComponent<RectTransform>();
selfV3 = transform.localPosition;
}
//当鼠标按下时调用 接口对应 IPointerDownHandler
public void OnPointerDown(PointerEventData eventData)
{
if (!lvRoot.isDrag) return;
Vector2 mouseDown = eventData.position; //记录鼠标按下时的屏幕坐标
Vector2 mouseUguiPos = new Vector2(); //定义一个接收返回的ugui坐标
bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDown, eventData.enterEventCamera, out mouseUguiPos);
if (isRect) //如果在
{
//计算图片中心和鼠标点的差值
offset = imgRect.anchoredPosition - mouseUguiPos;
}
}
//当鼠标拖动时调用 对应接口 IDragHandler
public void OnDrag(PointerEventData eventData)
{
if (!lvRoot.isDrag) return;
Vector2 mouseDrag = eventData.position; //当鼠标拖动时的屏幕坐标
Vector2 uguiPos = new Vector2(); //用来接收转换后的拖动坐标
//和上面类似
bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDrag, eventData.enterEventCamera, out uguiPos);
if (isRect)
{
//设置图片的ugui坐标与鼠标的ugui坐标保持不变
imgRect.anchoredPosition = offset + uguiPos;
imgRect.localScale = imgReduceScale; //缩小图片
}
}
//当鼠标抬起时调用 对应接口 IPointerUpHandler
public void OnPointerUp(PointerEventData eventData)
{
if (!lvRoot.isDrag) return;
offset = Vector2.zero;
imgRect.localScale = imgNormalScale; //回复图片
if(Vector3.Distance(Input.mousePosition, GameObject.Find("zhishideng3").transform.position) < 50f)
{
lvRoot.SetZhiModel(gameObject.name);
Destroy(gameObject);
}
else
{
transform.localPosition = selfV3;
}
//if (eventData.pointerCurrentRaycast.gameObject.name.Equals("zhishideng3"))
//{
// lvRoot.SetZhiModel(gameObject.name);
// Destroy(gameObject);
//}
//else
// transform.localPosition = selfV3;
}
//当鼠标结束拖动时调用 对应接口 IEndDragHandler
public void OnEndDrag(PointerEventData eventData)
{
if (!lvRoot.isDrag) return;
offset = Vector2.zero;
}
//当鼠标进入图片时调用 对应接口 IPointerEnterHandler
public void OnPointerEnter(PointerEventData eventData)
{
//Debug.LogError("OnPointerEnter");
//imgRect.localScale = imgReduceScale; //缩小图片
}
//当鼠标退出图片时调用 对应接口 IPointerExitHandler
public void OnPointerExit(PointerEventData eventData)
{
//Debug.LogError("OnPointerExit");
//imgRect.localScale = imgNormalScale; //回复图片
}
}
}