- Home /
Function to convert UI Position to actual position?
This is hard to put into words so I hope the picture helps. My guns are in my UI, as they are 2D sprites. Each gun may have a different position for it's muzzle so I want to draw a ray using the muzzle of the sprite and the players transform.forward.
I need to convert the UI's position from where it is in the canvas to where it is on the screen.
Please let me know if that makes sense, or is even possible.
I think that sometimes we imagine behaviours that don't exist. Your bottom image shows you hitting an object in the exact centre of the screen but if that enemy was a few meters back, still centred and you continued drawing your line it'd go off to the left. I think if you were to implement this behaviour it would feel very weird as the player would have to get the enemy in the top left part of the screen if they were far away. Since your gun is mostly aligned with the camera, I think that using the camera's forward ray as your bullet line will behave a lot more expectedly.
Thanks I see what you're saying, I'm actually using the players forward for hit detection. This will be for drawing a line renderer from the guns muzzle to the hit.point to imitate bullet trails.
Unless you have a different suggestion on a way to do this?
Answer by highpockets · Mar 12, 2021 at 10:20 PM
What you are going to want to use is Camera. ScreenToWorldPoint(new Vector3 (muzzPos.x, muzzPos.y, distanceFromCam));
. That will be your muzzle position translated to world space
Your setup potentially requires this instead RectTransformUtility.WorldToScreenPoint();
while passing camera as null
Thanks for the suggestions, these are what I've been trying to implement but I haven't been able to find the solution.
This is for casting a linerenderer from the muzzle to the raycasts hit.point. These are the implementations that I've tried.
Vector3 v = RectTransformUtility.WorldToScreenPoint(null, fps.firePoint.transform.position);
fps.lR.SetPosition(0, v);
Vector3 v = Camera.main.ScreenToWorldPoint(new Vector3(fps.firePoint.position.x, fps.firePoint.position.y, maxFireDist));
fps.lR.SetPosition(0, v);
Vector3 v = Camera.main.ScreenToWorldPoint(fps.firePoint.transform.position);
Your answer
![](https://koobas.hobune.stream/wayback/20220613030610im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to track a world object in a Screen Space - Camera Canvas 1 Answer
Find TextureCoordinates from plane with out raycast only using mouse position on plan 0 Answers
How to achieve a more accurate Mouse to WorldCoordinates & faster updating of object follow? 2 Answers
Raycast, ScreenToWorldPoint accuracy problem 4 Answers
Camera.main.ScreenToWorldPoint not outputting expected results. 1 Answer