- Home /
World to Screen
So I am having a problem trying to get World coordinates to Screen Coordinates. I have the function, but when ever I attempt it the GUI labels always end up WAY off the target GameObject. Here is my OnGui:
var posVector = Camera.main.WorldToScreenPoint(transform.position);
var labelRect : Rect;
labelRect.x = posVector.x;
labelRect.y = posVector.y;
labelRect.width = 50;
labelRect.height = 20;
GUI.Label(labelRect,lifeLeft.ToString());
Kinda confused. BTW my camera is on orthogonal if that makes a difference
Thanks
EDIT:
var posVector = Camera.main.WorldToScreenPoint(transform.position);
var vectorTwo : Vector2 = GUIUtility.ScreenToGUIPoint(new Vector2(posVector.x,posVector.y));
var labelRect : Rect;
labelRect.x = vectorTwo.x;
labelRect.y = vectorTwo.y;
labelRect.width = 20;
labelRect.height = 20;
GUI.Label(labelRect,lifeLeft.ToString());
Answer by Blankzz · Aug 10, 2011 at 11:24 PM
WorldToScreenPoint gives you a point in Screen space you need to get the point in GUI space.
labelRect.y = Screen.height - posVector.y;
OR use;
GUIUtility.ScreenToGUIPoint(new Vector2(posVector.x, posVector.y));
Thanks man, But its not working 100%. The labels y coord is all messed up.
Ill edit the original post with the new code to see if I am doing it wrong
I just remembered that I could never get ScreenToGUIPoint to work for me. I asked a similar question when starting so I know my first solution should work. http://answers.unity3d.com/questions/142125/screentoguipoint.html
Ok now I tried Screen.height - y and Screen.width - x and now the x is off... so confused
You don't need to do anything with the x coordinate. Screen coordinates are (0,0) at top left of screen and GUI coordinates are (0,0) at bottom left of the screen so you only need to convert the y value.
Your answer
Follow this Question
Related Questions
How to get the screen position in an unlit shader. 1 Answer
Screen point to point on Plane WITHOUT Raycast? 1 Answer
Keeping the player inside the screen? 2 Answers
Position GameObject to Bottom Left Corner 2 Answers
A node in a childnode? 1 Answer