ZhangZhouSpecialEquipment/Assets/Scripts/锅炉/MultiSubCanvasClickHandler.cs

88 lines
3.1 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MultiSubCanvasClickHandler : MonoBehaviour
{
public static MultiSubCanvasClickHandler Instance;
public Camera targetCamera; // 目标相机,用于发射射线
public RawImage rawImage; // 需要判断点击位置的 RawImage
public float maxRaycastDistance = 100f; // 射线最大检测距离
public bool IsUse=false;
private void Awake()
{
Instance = this;
}
void Update()
{
if(IsUse)
{
// 检测鼠标左键按下事件
if (Input.GetMouseButtonDown(0))
{
// 获取鼠标点击位置
Vector2 mousePosition = Input.mousePosition;
// 将鼠标点击位置转换为 RawImage 的局部坐标
RectTransformUtility.ScreenPointToLocalPointInRectangle(
rawImage.rectTransform,
mousePosition,
null,
out Vector2 localPoint//返回的局部坐标
);
// 将局部坐标转换为归一化坐标,通过RawImage的长宽比
Rect rect = rawImage.rectTransform.rect;
float normalizedX = (localPoint.x - rect.x) / rect.width;
float normalizedY = (localPoint.y - rect.y) / rect.height;
// 打印归一化坐标
//Debug.Log($"Click Position: ({normalizedX}, {normalizedY})");
// 判断点击位置是否在 RawImage 范围内
if (normalizedX >= 0 && normalizedX <= 1 && normalizedY >= 0 && normalizedY <= 1)
{
//Debug.Log("Click is within RawImage bounds.");
// 将归一化坐标转换为目标相机画面的屏幕坐标
Vector3 screenPoint = new Vector3(
normalizedX * targetCamera.pixelWidth,
normalizedY * targetCamera.pixelHeight,
targetCamera.nearClipPlane
);
// 从目标相机发射射线
Ray ray = targetCamera.ScreenPointToRay(screenPoint);
RaycastHit hit;
// 绘制射线,无论是否击中物体
if (Physics.Raycast(ray, out hit, maxRaycastDistance))
{
// 如果射线打中了某个物体
//Debug.Log("Hit: " + hit.transform.gameObject.name);
GuoLuHowMsgs.Instance.ShowCoreMsg(hit.transform.gameObject.name);
// 绘制射线到击中点
//Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.red, 5);
}
else
{
// 如果射线没有击中任何物体,绘制射线到最大距离
//Debug.Log("Hit: Nothing");
//GuoLuHowMsgs.Instance.ShowCoreMsg("Nothing");
// 绘制射线到最大距离
//Debug.DrawRay(ray.origin, ray.direction * maxRaycastDistance, Color.red, 5);
}
}
}
}
}
}