- Home /
I am trying to shoot a ray from an game object on a canvas.
Hey! I am trying to shoot a raycast from a UI image but I cannot figure out how to do so. I have tried using a graphic raycaster but I only was able to get it to shoot from my mouse position. I've attached an image to further show my issue, the red dot is where I need the ray to be shot from and the blue arrow is the direction it needs to go. Does anyone know of any solutions?
Answer by Aluminum18 · Jan 05 at 03:47 AM
Vector3 screenPoint = yourMainCamera.WorldToScreenPoint(yourRedDotTransform.position);
Ray aimRay = yourMainCamera.ScreenPointToRay(screenPoint);
Physics.Raycast(aimRay, out var hit, _maxRayDistance);
// Do something with hit object
The idea is to convert your reddot position in scene into position in screen, then use screen position to do raycast
Hi, I've used that but it doesn't seem to be working.
if (Input.GetMouseButtonDown(0))
{
Vector3 screenPoint = cam.WorldToScreenPoint(ringOneLine.transform.position);
Ray aimRay = cam.ScreenPointToRay(screenPoint);
Physics.Raycast(aimRay, out var hit, maxRayDistance);
Vector3 forward = ringOneLine.transform.TransformDirection(Vector3.forward) * 100;
Debug.DrawRay(ringOneLine.transform.position, forward, Color.red);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613051303im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can we import a canvas from unity 2020 into unity 2018? 1 Answer
Transform translate not working properly in Canvas 0 Answers
Unity UI not showing some Images 0 Answers
Image Displaying Bleached Texture. 0 Answers
Create UI Mask from Childrens images 2 Answers