🗂
UI Toolkit でスクリーン座標に Element があるか調べる
Unity でゲームを作っているときに、画面をタップしたら Ray を飛ばしてそのスクリーン座標の先にオブジェクトがあるかを調べるということがあると思いますが、UI Toolkit でボタンなどを配置しているときに、その下のオブジェクトには反応したくないといった場合、ボタン上にタップした座標があるかを調べる方法です。
Vector3 hitPosition // Ray がヒットした座標
public UIDocument uiDocument; // UIDocument の参照
// ボタン
VisualElement element = uiDocument.rootVisualElement.Q<Button>("Button");
// スクリーン座標
Vector3 pointerPosition = Camera.main.WorldToScreenPoint(hitPosition);
// UI Toolkit の座標原点はスクリーン座標と上下逆なので変換
Vector2 screenPosition = new Vector2(pointerPosition.x, Screen.height - pointerPosition.y);
VisualElement rootElement = uiDocument.rootVisualElement;
// スクリーン座標を UI Toolkit の座標に変換
Vector2 panelPosition = RuntimePanelUtils.ScreenToPanel(rootElement.panel, screenPosition);
// VisualElement の矩形
Rect rect = element.worldBound;
if (rect.Contains(panelPosition))
{
return true;
}
return false;
Discussion