AK056/Assets/GameLogic/Origin/event/EventCompent.cs

143 lines
3.7 KiB
C#

using EasyInject.Attributes;
using NUnit.Framework;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 监听处理组件
/// </summary>
[GameObjectBean]
public sealed class EventCompent : MonoBehaviour
{
private float lastClickTime = 0f;
private const float DOUBLE_CLICK_INTERVAL = 0.5f;
public delegate void MouseClickEvent();
public event MouseClickEvent MouseClickEvents;
public event MouseClickEvent MouseDoubleClickEvents;
private void Start()
{
List<IMouseClick> mouseClicks = ApplicationBoot.Instance.GetBeans<IMouseClick>();
foreach (IMouseClick click in mouseClicks)
{
MouseClickEvents += click.MouseSingleClick;
MouseDoubleClickEvents += click.MouseDoubleClick;
}
}
private void Update()
{
GlobalMouseRayHandle();
}
/// <summary>
/// 全局射线点击监听
/// </summary>
private void GlobalMouseRayHandle()
{
if (Input.GetMouseButtonDown(0))
{
CheckDoubleClick();
}
}
void CheckDoubleClick()
{
// 双击时执行的操作(如创建物体)
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
float currentTime = Time.time;
if (currentTime - lastClickTime <= DOUBLE_CLICK_INTERVAL)
{
// 双击事件
OnDoubleClick(hit);
return;
}
else
{
// 单击事件
OnSingleClick(hit);
}
lastClickTime = currentTime;
}
}
private void OnDoubleClick(RaycastHit hit)
{
GameObject clickTarget = hit.collider.gameObject;
MonoBehaviour[] monoBehaviours = clickTarget.GetComponents<MonoBehaviour>();
if(monoBehaviours == null)
{
return;
}
if ( monoBehaviours.Length < 1)
{
MonoBehaviour[] monos = clickTarget.GetComponentsInParent<MonoBehaviour>();
CheckDoubleClickTrigger(monos);
}
else
{
CheckDoubleClickTrigger(monoBehaviours);
}
}
private void OnSingleClick(RaycastHit hit)
{
// 单击时执行的操作
GameObject clickTarget = hit.collider.gameObject;
MonoBehaviour[] monoBehaviours = clickTarget.GetComponents<MonoBehaviour>();
if (monoBehaviours == null)
{
return;
}
if (monoBehaviours.Length < 1)
{
MonoBehaviour[] monos = clickTarget.GetComponentsInParent<MonoBehaviour>();
CheckSingleClickTrigger(monos);
}
else
{
CheckSingleClickTrigger(monoBehaviours);
}
}
private void CheckDoubleClickTrigger(MonoBehaviour[] behaviours)
{
foreach (var ev in MouseDoubleClickEvents?.GetInvocationList())
{
if (ev.Target is MonoBehaviour mono)
{
foreach(var behav in behaviours)
{
if (mono == behav)
{
ev.DynamicInvoke();
}
}
}
}
}
private void CheckSingleClickTrigger(MonoBehaviour[] behaviours)
{
foreach (var ev in MouseClickEvents?.GetInvocationList())
{
if (ev.Target is MonoBehaviour mono)
{
foreach (var behav in behaviours)
{
if (mono == behav)
{
ev.DynamicInvoke();
}
}
}
}
}
}