- Home /
Conversion from world to screen space not right?
I'm having trouble showing a box at a certain position on the screen based on the position of an object in world space. I have a text-balloon GameObject above one of my NPC's and I want to write text in it by code.
I had this code to do that:
Rect textFieldRect = new Rect(new Vector2(balloonPos.x, balloonPos.y), new Vector2(100, 100));
Rect screenspacePos = new Rect(GameObject.Find("Camera").GetComponent<Camera>().WorldToScreenPoint(new Vector3(textFieldRect.x, textFieldRect.y, 0)), new Vector2(textFieldRect.width, textFieldRect.height));
GUI.Box(screenspacePos, text);
but this doesn't seem to work as I expected. I can see the text showing up but it's not on top of the balloon as you can see in this screenshot: Imgur Link
I am probably doing something wrong with the conversion? The balloonPos data is right (I checked this).
Answer by Eric5h5 · Nov 06, 2015 at 11:58 PM
The conversion is correct, but your code can't work like that. The point of the conversion is that you put in a world coordinate and get a screen coordinate back, but you're making a new coordinate by stripping out the Z element, which is important. You need to supply a direct, unmodified world coordinate in order for the function to work.
As an additional note, another likely problem is that the Y-axis is probably flipped. It may be necessary to use something like
screenspacePos.y = (Screen.height - screenspacePos.y);
in order to get the correct vertical position.
I had the same problem recently with my custom camera rig. Zoo$$anonymous$$g out would misaligne the point but using @$$anonymous$$o-Khaon 's note fixed the issue.
Your answer
Follow this Question
Related Questions
Is there an alternative to Camera.WorldToScreenPoint or another way to solve this problem? 0 Answers
Recreating basic function in C# 1 Answer
Zoom in on tapped point in 3D space 1 Answer
Js to c# conversion 1 Answer
How to scale down the camera 0 Answers