Last active
July 13, 2023 06:35
-
-
Save RoxDevvv/83215ae2fe45c5e7416521fe1697fb03 to your computer and use it in GitHub Desktop.
Unity Xr and UI element world space
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using UnityEngine.UIElements; | |
using UnityEngine.XR.Interaction.Toolkit; | |
public class XrRay2UIelement : MonoBehaviour | |
{ | |
UIDocument document; | |
[SerializeField] private XRRayInteractor rayInteractor; | |
private void Start() | |
{ | |
document = GetComponent<UIDocument>(); | |
var invalidPos = new Vector2(float.NaN, float.NaN); | |
var Cursor = document.rootVisualElement.Q<VisualElement>("Cursor"); | |
MeshRenderer quadRenderer = GetComponent<MeshRenderer>(); | |
RaycastHit hit; | |
Vector2 PixelUV; | |
document.panelSettings.SetScreenToPanelSpaceFunction((Vector2 ScreenPos) => | |
{ | |
if (!rayInteractor.TryGetCurrent3DRaycastHit(out hit) | |
|| !quadRenderer.bounds.Contains(hit.point)) | |
{ | |
Debug.Log("invalid position"); | |
Cursor.visible = false; | |
return invalidPos; | |
} | |
PixelUV = hit.textureCoord; | |
PixelUV.y = 1 - PixelUV.y; | |
PixelUV.x *= document.panelSettings.targetTexture.width; | |
PixelUV.y *= document.panelSettings.targetTexture.height; | |
Cursor.visible = true; | |
Cursor.style.left = PixelUV.x; | |
Cursor.style.top = PixelUV.y; | |
return PixelUV; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment