- Home /
Raycast from GUI element
How would I raycast from a GUI element? For example, I have a crosshair that lazily follows the center of the screen or can be offset according to the needs of the player. I would like to keep raycasting from the crosshairs regardless of where it is at that moment.
I have tried
camera.ViewportToWorldPoint(guiRect.anchoredPosition);
To no avail.
Note that the crosshair is parented to several other UI elements which also move.
Thanks for your time.
Answer by ethestel · Apr 07, 2015 at 07:34 AM
Hello,
Try this:
Ray ray = Camera.main.ScreenPointToRay(uiObject.transform.position);
I used that and it worked well back when I had GUITextures but nothing happens with 4.6 GUI elements.
To debug if ray is working or not, you can add this script to any game object
using UnityEngine;
using UnityEngine.UI;
public class RayFrom : $$anonymous$$onoBehaviour {
private Ray m_ray;
public RectTransform r_canvasElementTransform;
void Update()
{
m_ray = Camera.main.ScreenPointToRay(r_canvasElementTransform.position);
}
void OnDrawGizmos() {
Gizmos.color = Color.yellow;
Gizmos.DrawRay(m_ray.origin, m_ray.direction*1000f);
}
}
and reference the GUI element you want to shoot ray from. When you go into play mode, you should see a yellow line go out from your camera object on editor view. Try moving the canvas element around to test if yellow line is moving
It seems to be shooting towards the bottom left corner of the screen or towards the sky and rightwards.
This happens to both viewport.ViewportPointToRay(crosshairRect.position) and viewport.ViewportPointToRay(crosshairRect.anchoredPosition)
All I really need is a way to get a UI element's canvas position and convert it to viewport position so I can cast a ray from it.
Close enough. In $$anonymous$$e, the ray comes from the camera and is aligned with the lower left corner frustum with
viewport.ViewportPointToRay(crosshairRect.anchoredPosition)
while
viewport.ViewportPointToRay(crosshairRect.position)
makes the ray go from the camera to the center of the canvas in world space.
I just noticed I had put ViewportPointToWorld in the OP. That's a mistake. xD