Frame/Assets/Scripts/RayCast/MouseInput.cs

107 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
namespace Game.RayCast;
public class MouseInput : MonoBehaviour
{
public RayCastType rayCastType = RayCastType._2D;
MouseInputData mouseInputData = new MouseInputData();
// public event MouseInputEventHandle ev;
private void Update()
{
if (this.IsMouseOverUI()) return;
switch (rayCastType)
{
case RayCastType._3D:
// 3d
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider != null)
{
Debug.Log(hit.collider.name);
}
}
break;
case RayCastType._2D:
//2d
var point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var hit2D = Physics2D.Raycast(point, -Vector2.up);
if (hit2D.collider != null)
{
if (Input.GetMouseButtonDown(0))
{
UnityEngine.Debug.Log(hit2D.collider.name);
mouseInputData.rayCastType = this.rayCastType;
mouseInputData.point = hit2D.point;
mouseInputData.isPressDown = true;
mouseInputData.go = hit2D.collider.gameObject;
EventManager.Instance.FireNow(this, new InputObjectFinishEventArgs(mouseInputData));
}
else if (Input.GetMouseButtonDown(2))
{
// Game.bfsManager.Test(hit2D.point);
}
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private bool IsMouseOverUI()
{
PointerEventData eventData = new PointerEventData(EventSystem.current)
{
position = Input.mousePosition
};
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, results);
foreach (var result in results)
{
// 检查射线检测到的对象是否为UI元素并且是否属于CanvasGroup
CanvasGroup canvasGroup = result.gameObject.GetComponentInParent<CanvasGroup>();
if (canvasGroup != null)
{
// 如果CanvasGroup不允许交互或不阻挡射线我们认为鼠标不是位于UI上
if (!canvasGroup.interactable || !canvasGroup.blocksRaycasts)
{
continue;
}
}
// 如果找到至少一个允许交互且阻挡射线的UI元素返回true
return true;
}
// 如果所有射线检测到的UI元素都不允许交互或不阻挡射线返回false
return false;
}
}
public enum RayCastType
{
_3D,
_2D,
}
public class MouseInputData
{
public RayCastType rayCastType;
public bool isPressDown;
public Vector3 point;
public GameObject go;
}