- Home /
How can I get a ray working with new UI system?
The ray in the image below is supposed to fire exactly through the center of a moving little green square. The 2d square (FinalTargetLocator GameObject )is an image with a rectTransform in my canvas. The canvas use Screen Space - Camera.
I've tried lots of variants to get this working but nothing has been accurate. The closest I have come uses the following code but the ray is alway cast further from the centra of the screen than the green square. The further the square is from the centre of the screen, the more innacurate the ray. Infact the ray actually only seems to touch the green square at when the square is dead centre.
finalTargetX=(finalTargetRectTransform.anchoredPosition.x +(Screen.width/2));//
finalTargetY=(finalTargetRectTransform.anchoredPosition.y + (Screen.height/2));
ray = UICamera.ScreenPointToRay (Vector3(finalTargetX,finalTargetY,0));
Debug.DrawRay(ray.origin, ray.direction*1000, Color.blue);
how is the green rect anchored? $$anonymous$$anual says:
If the anchors are not together, the four anchor positions are interpolated according to the pivot placement.
kd -As far as I know I can only cast a ray from the camera to an object right? That's why I'm trying to cast from camera to the green square..
hrungdak - the pivot is right in the center of the object. see attached..
Sorry, grimmy. I have rebuilt the scene and it works perfect.
The ray runs through the center of the target and if i move the target the ray follows exactly the center of it. I took the main Camera for the test, i don't know if your cam is the main. Is there is something wrong with your cam?
I had the effect that the ray wandered double or triple the way as the target. This was when the target was embedded in a panel that was smaller than the canvas. Solution was to divide finalTargetX and Y by Canvas.panelDistance (for what reason ever...). But without panel it works with your code.
Your answer
![](https://koobas.hobune.stream/wayback/20220613193240im_/https://answers.unity.com/themes/thub/images/avi.jpg)