OnPointUp 不仅鼠标松开会调用,鼠标移动也会调用。 时间紧迫,只贴核心代码
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using System;
namespace Scripts.LuaApi
{
public class DragItemArea : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler
{
public Graphic checkArea;
public Graphic copyItem;
private const string UI_CameraPath = "Root/_GameManager(Clone)/UGUISystem/Camera";
private Camera UICamera;
public Action<Graphic,object> beginEvent;
public Action<object> endInAreaCallback;
public Action<object> endCallback;
private bool inEnter = false;
public UnityEvent inEvent;
public UnityEvent outEvent;
public object data;
private Vector2 lastMousePosition;
public void SetBeginEvent(Action<Graphic,object> be)
{
this.beginEvent = be;
}
public void ResetEvent()
{
beginEvent = null;
endInAreaCallback = null;
endCallback = null;
}
public void SetEndInAreaCallback(Action<object> ee)
{
this.endInAreaCallback = ee;
}
public void SetEndCallback(Action<object> callbcak)
{
this.endCallback = callbcak;
}
public void SetData(object data)
{
this.data = data;
}
private void Start()
{
if (UICamera == null)
{
var camera = GameObject.Find(UI_CameraPath);
if (camera != null)
{
UICamera = camera.GetComponent<Camera>();
}
else
{
Debug.LogError($"当前场景路径找不到 UI 摄像机 路径 = {UI_CameraPath} 请检查");
}
}
}
private bool IsInArea(Vector2 screenPoint)
{
return RectTransformUtility.RectangleContainsScreenPoint(checkArea.rectTransform, screenPoint,UICamera);
}
public void OnBeginDrag(PointerEventData eventData)
{
lastMousePosition = eventData.position;
beginEvent?.Invoke(copyItem, data);
}
public void OnDrag(PointerEventData eventData)
{
if (copyItem != null)
{
Vector2 mousePosition = eventData.position;
#if UNITY_ANDROID && !UNITY_EDITOR
mousePosition = Input.GetTouch(0).position;
#endif
Vector2 delta = mousePosition - lastMousePosition;
((RectTransform)transform).anchoredPosition += delta;
lastMousePosition = mousePosition;
if (IsInArea(mousePosition))
{
if(!inEnter)
{
inEvent?.Invoke();
inEnter = true;
}
}
else
{
if (inEnter)
{
outEvent?.Invoke();
inEnter = false;
}
}
}
}
public void OnEndDrag(PointerEventData eventData)
{
if (IsInArea(eventData.position))
{
endInAreaCallback?.Invoke(data);
}
inEnter = false;
endCallback?.Invoke(data);
outEvent?.Invoke();
}
}
}
|