Files
Rhyculator/Assets/Script/UIHitTest.cs
T
2026-10-24 11:55:22 +08:00

53 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// 找出螢幕某點最上層的 UI 圖形(不依賴 EventSystem,主畫面沒有 EventSystem)
public static class UIHitTest
{
// 該點最上層是否為「格子以外」的 UI(面板、按鈕、圖片…),是的話格子不該接收這次觸控
// 文字不視為阻擋物(例如 UID、版本號、分數)
public static bool IsBlocked(Vector2 screenPos, IList<Transform> gridRoots)
{
Graphic top = TopmostGraphicAt(screenPos);
if (top == null) return false;
foreach (var root in gridRoots)
if (root != null && top.transform.IsChildOf(root)) return false;
return true;
}
public static Graphic TopmostGraphicAt(Vector2 screenPos)
{
Graphic top = null;
long topKey = long.MinValue;
foreach (var canvas in Object.FindObjectsByType<Canvas>(FindObjectsSortMode.None))
{
if (!canvas.isActiveAndEnabled) continue;
Canvas root = canvas.rootCanvas;
bool overlay = root.renderMode == RenderMode.ScreenSpaceOverlay;
Camera cam = overlay ? null : root.worldCamera;
var graphics = GraphicRegistry.GetRaycastableGraphicsForCanvas(canvas);
for (int i = 0; i < graphics.Count; i++)
{
Graphic g = graphics[i];
if (g is Text) continue;
if (!g.isActiveAndEnabled || g.depth < 0 || g.canvasRenderer.cull) continue;
if (!RectTransformUtility.RectangleContainsScreenPoint(g.rectTransform, screenPos, cam)) continue;
// 排序:Overlay 畫布在最上層 → 畫布 sortingOrder → 畫布內繪製順序
long key = ((overlay ? 1L : 0L) << 48) + ((long)(canvas.sortingOrder + 32768) << 24) + g.depth;
if (key > topKey)
{
topKey = key;
top = g;
}
}
}
return top;
}
}