using System;
|
using UnityEngine;
|
using UnityEngine.EventSystems;
|
using System.Collections.Generic;
|
|
namespace vnxbqy.UI
|
{
|
[DisallowMultipleComponent]
|
public class DragSelectComponentEx : MonoBehaviour
|
{
|
[SerializeField] float m_Sensitive = 10f;
|
[SerializeField] GameObject m_TargetObject;
|
|
public event Action<int> onDragComplete;
|
|
private bool m_StartDrag = false;
|
|
Vector3 start_position = Vector3.zero;
|
bool isArea = false;
|
|
private void LateUpdate()
|
{
|
if (Input.touchCount > 1)
|
{
|
m_StartDrag = false;
|
return;
|
}
|
if (Input.GetMouseButtonDown(0))
|
{
|
m_StartDrag = true;
|
start_position = Input.mousePosition;
|
isArea = RectTransformUtility.RectangleContainsScreenPoint(this.transform as RectTransform, start_position, CameraManager.uiCamera);
|
if (!IsOverTarget())
|
{
|
m_StartDrag = false;
|
return;
|
}
|
}
|
else if (Input.GetMouseButtonUp(0) && m_StartDrag)
|
{
|
var delta = Input.mousePosition - start_position;
|
m_StartDrag = false;
|
|
// 判断滑动方向
|
if (Mathf.Abs(delta.x) >= m_Sensitive || Mathf.Abs(delta.y) >= m_Sensitive)
|
{
|
int direction = 0;
|
|
// 水平方向优先
|
if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
|
{
|
direction = delta.x > 0 ? 1 : -1; // 1 表示向右滑动,-1 表示向左滑动
|
}
|
// 垂直方向优先
|
else
|
{
|
direction = delta.y > 0 ? 2 : -2; // 2 表示向上滑动,-2 表示向下滑动
|
}
|
|
// 新增目标对象检测条件
|
if (onDragComplete != null && isArea)
|
{
|
onDragComplete(direction);
|
}
|
}
|
}
|
}
|
|
// 新增目标检测方法
|
private bool IsOverTarget()
|
{
|
if (m_TargetObject == null) return true;
|
|
PointerEventData eventData = new PointerEventData(EventSystem.current)
|
{
|
position = Input.mousePosition
|
};
|
|
List<RaycastResult> results = new List<RaycastResult>();
|
EventSystem.current.RaycastAll(eventData, results);
|
|
if (results.Count > 0)
|
{
|
RaycastResult result = results[0];
|
if (result.gameObject == m_TargetObject)
|
{
|
return true;
|
}
|
if (result.gameObject.transform.parent.gameObject == m_TargetObject)
|
{
|
return true;
|
}
|
}
|
return false;
|
}
|
|
private void OnDisable()
|
{
|
m_StartDrag = false;
|
}
|
}
|
}
|