Tz2/Assets/Zion/Scripts/Utility/DragWindow.cs

72 lines
2.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DragWindow : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler, IPointerClickHandler
{
Vector3 offest;
bool CanDrag = false;
bool isFirstDrag = true;
/// <summary>
/// 是否忽略是否在UI上保持可拖动
/// </summary>
[Header("是否忽略是否在UI上保持可拖动")]
public bool IgnoretheUI = false;
//刚开始拖拽时第一下触发这个函数
public void OnBeginDrag(PointerEventData eventData)
{
if (!IgnoretheUI)
if (EventSystem.current.IsPointerOverGameObject()) return;
if (RectTransformUtility.RectangleContainsScreenPoint(transform as RectTransform, Input.mousePosition))
{
//1、计算所有需要的数据 image本身的坐标 鼠标所在的位置相对于Canvas的本地坐标
Vector2 localPos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(transform as RectTransform, Input.mousePosition, null, out localPos);
//2、计算偏移量
offest = vector2TpVector3(localPos);
CanDrag = true;
}
}
Vector3 vector2TpVector3(Vector2 vector2)
{
return new Vector3(vector2.x, vector2.y, 0);
}
public void OnDrag(PointerEventData eventData)
{
if (!IgnoretheUI)
if (EventSystem.current.IsPointerOverGameObject()) return;
if (CanDrag)
{
Vector2 localPosition;
RectTransformUtility.ScreenPointToLocalPointInRectangle(transform.parent as RectTransform, Input.mousePosition, null, out localPosition);
//transform.localPosition = localPosition;
// offest = vector2TpVector3(localPosition);
transform.localPosition = vector2TpVector3(localPosition) - offest;
}
}
//停止拖拽
public void OnEndDrag(PointerEventData eventData)
{
if (!IgnoretheUI)
if (EventSystem.current.IsPointerOverGameObject()) return;
CanDrag = false;
if (isFirstDrag && transform.Find("tip"))
{
transform.Find("tip").gameObject.SetActive(false);
isFirstDrag = false;
}
}
public void OnPointerClick(PointerEventData eventData)
{
}
}