Constant size GUI image floating above objects
I'm trying to make some kind of indicator ( icon) that is floating above each "enemy" object. It's relatively easy if I attach world space canvas with an image to my object. However I need some hint which would help me keep the icon size fixed regardless of the distance to the camera.
You can see the exact thing I'm trying to make on this video: example video
or this image:
It looks like the only thing I need to do is to get my enemy position on the screen and assign it to my icon. Something like this:
Vector3 screenPos = Camera.main.WorldToScreenPoint(enemy.position);
icon.localPosition = screenPos;
Unfortunately it's not working as expected. That is because (0,0) point for screen is located in lower left corner while if I set the same coordinates for my image it is displayed exactly in the middle of the screen.
Can anyone help me to overcome this issue ? What is the right canvas / icon setup to achieve this result using Unity GUI system ?
Answer by Krzysztof-P · May 04, 2016 at 05:52 PM
Well... it's the second time I'm answering my own question but since the answer was not that easy to find ( I found a lot unanswered questions about RectTransform elements positioning and scaling behavior ) I decided to put solution over here.
Basically If you access RecTransform component and try to deal with it's position you will have to take all the variable factors into consideration ( pivot, anchor, local position, global position, screen size etc... )
The easy solution for that would be to access transform component instead. Pretty much like this:
Vector3 screenPos = Camera.main.WorldToScreenPoint(enemy.position);
icon.transform.position =screenPos;
Your answer
Follow this Question
Related Questions
i want to browse a picture from a directory to be used as a username login. 0 Answers
How to make Canvas appear after GUI texture? Unity 4.7 1 Answer
What am I doing wrong? 0 Answers
Toggle Button: hope it toggle once but it toggle many times 1 Answer
How to change the small circle in google cardboard with another texture? 0 Answers