I was trying to get a GUI texture hovering above an object’s position. My problem was that the texture was changing in the y-axis while being placed correctly in the x-axis. After hours of trials, errors and searching the web I finally managed to get it right.
Vector3 p = Camera.main.WorldToScreenPoint (gameObject.transform.position);
p.y = Screen.height - p.y;
GUI.DrawTexture(new Rect((p.x + offsetX), (p.y + offsetY), (0 + width), (height + height)),ttext);
Apparently I did not have the “p.y = Screen.height - p.y” in my first examples. With it it works like a charm. My question is why “p.y = Screen.height - p.y” did the trick? Can someone explain what that piece of code actually does? Why is it only necessary for the y-coordinate and not for the x like “p.x = Screen.width - p.x”? I would really appreciate if someone could explain this to me as I have no idea why it works now…
The documentation is kind of odd on this - one place says that screen space y starts with 0 at the bottom, and another that starts with 0 at the top. I can never remember and have to figure it out each time. I believe the former is correct.
Regardless, you’re dealing with two different spaces here. WorldToScreenPoint gives you screen space, but the GUI drawing apparently works in GUI space where the y is flipped - i.e. 0 at the bottom for screen space, 0 at the top for GUI space. So you have to transform between the spaces.
You should be able to use the GUIUtility.ScreenToGUIPoint to transform your screen space point into GUI space, rather than flipping y yourself.
Well, that’s simple ^^. The Screen-space which Unity (any most other engines uses) has the origin at the bottom left corner of the screen. It’s the usual device coordinate system. So the x-axis goes from left to right and the y-axis goes from bottom to top.
The GUI-space however has it’s origin at the top left corner. So if you want to convert a screen space position into GUI space you just have to subtract the position from the screen height so you know where the point is in GUI space.