- Home /
Drawing GUI rectangle uses negative y coordinate
I have a function to draw a healthbar on top of my players, and I'm using WorldToScreenPoint to draw it just above them. It draws the healthbar at the appropriate x coordinate, but somehow it's drawing it at the opposite y coordinate. For example if my player is at a y of 1, the healthbar will be at -1, and as the player's y rises, the healthbar's y lowers. Here is the code I use:
function OnGUI()
{
var screenPos : Vector3 = Camera.main.WorldToScreenPoint (transform.position);
// draw the background:
GUI.BeginGroup (new Rect (screenPos.x, screenPos.y, size.x, size.y));
GUI.Box (Rect (0,0, size.x, size.y),healthBarEmpty);
// draw the filled-in part:
GUI.BeginGroup (new Rect (0, 0, (size.x * health) / 100, size.y));
GUI.Box (Rect (0,0, size.x, size.y), healthBarFull);
GUI.EndGroup ();
GUI.EndGroup ();
}
Also, using the negative of the y position seems to just make the GUI disappear altogether. Anyone see what's wrong?
Answer by robertbu · Aug 23, 2014 at 03:48 AM
GUI coordinates and Screen coordinates are not the same. Both are pixels, but GUI coordinates start in the upper left corner, where Screen coordinates start in the lower left corner. Insert at line 5:
screenPos.y = Screen.height - screenPos.y;
Your answer
Follow this Question
Related Questions
OnGUI() not being called in Monobehaviour 1 Answer
2D GUI Group moving with players. 1 Answer
Can you make a GUI.Box follow a player's position?(SOLVED) 7 Answers
Non-square camera preview 0 Answers