- Home /
Why doesn't my ray collide with a GUI Text?
I'm using Leap Motion to set the position of a GUI texture on the screen. When I select this position I shoot a ray from the camera to the GUI texture's position but it does not collide with the GUI text that's under it. If I use a 3D text it does work. The GUI text has a box collider.
I'm using:
RaycastHit hit;
Ray testRay = Camera.main.ViewportPointToRay (guiTexture.transform.position);
if (Physics.Raycast (testRay, out hit))
{
...
}
Any Thoughts? Thanks
Answer by robertbu · Feb 21, 2014 at 01:37 AM
GUIText and GUITexture objects live in Viewport space, so your box collider will not work. You have a few choices depending on your needs. First OnMouse* callback functions work with GUIText and GUITexture objects. Second you can do the hit test using GUIElement.HitTest(). Something like:
if (guiText.HitTest(Input.mousePosition)) {
Debug.Log("Clicked");
}
A third choice is to have an empty game object with a box collider in the scene that tracks the GUIText element. You would need to decide the distance from the camera for this element and then use Camera.ViewportToWorldPoint() to position the empty object. You likely want to do this tracking in LateUpdate().
Thanks. I'm using your second option
Vector3 position = new Vector3
(guiTexture.transform.position.x * UnityEngine.Screen.width,
guiTexture.transform.position.y * UnityEngine.Screen.height,
0);
if (button.HitTest(position))
{
..
}