Super Weird GUI Positioning Problem

Alright, I’ll try to explain this as simply as possible. I have two players that i want to put health bars over. After executing the code below, the results were NOT what I expected. for health bars 1 and 2:

Player 1 controls: 1.x, and 2.y

Player 2 controls: 2.x and 1.y

To try and troubleshoot the problem, I added a third player… this did not help.

Player 3 controls: 3.x and 3.y … but the y is INVERTED on the healthbar…

void OnGUI()
{

	if (Event.current.type.Equals (EventType.Repaint)) 
	{  //Is the game being drawn?	
			
		GUI.skin = playerName;
		foreach (GameObject target in players) 
		{
			Vector3 thisTransform= camera.WorldToScreenPoint(target.transform.position);
			stats thisGuy = target.GetComponent<stats>();
			float healthy = (thisGuy.health/thisGuy.maxhealth);
		
			Rect container = new Rect (thisTransform.x, thisTransform.y, 300, 95);
			Rect health = new Rect (thisTransform.x+8, thisTransform.y+49, 249*healthy, 23);
			Rect mana =new Rect (thisTransform.x+8, thisTransform.y+79, 249, 9);
			Rect name = new Rect(thisTransform.x+8, thisTransform.y+9, 249, 32);
			Graphics.DrawTexture (container, bg);
			Graphics.DrawTexture (health, healthMat);
			Graphics.DrawTexture (name, thisGuy.playerColor);

			Graphics.DrawTexture (container, overlay);
									
			GUI.Label(name, thisGuy.playerName);						
									
									
		}
				
	}
}

the rest of the GUI draws properly, everything is fine except the position tracking.

Super-expected and documented behaviour, actually…

  • WorldToScreenSpace returns a pixel position in screen space in which (0,0) is the bottom left hand corner.

  • GUI functions are expressed in pixel coordinates in which (0,0) is the top left hand corner.

And a simple Google search would have revealed a duplicate question with the simple answer; use Screen.height - screenPos.y to invert the y axis.