RTS healthbar (GUI box follow GameObject) with perspective camera

Hello , i’l be brief and get to the subject :
The following script draws HP bars for RTS-like game.
It does work well with Orthografic camera (since it has a rectangular viewport). But when i hook in an Perspective camera, the box is drawn with an slight (but noticeable offset) especially noticeable when the component that has the HP bar attached is near the screen edge. I guess it’s related to the pyramidal projection of the camera.

using UnityEngine;
using System.Collections;


public class Attackable : MonoBehaviour {
	public float maxHp;
	public float currentHp;
	public Camera     mainCamera;
	public Texture2D  hpBarBG;
	public Texture2D  hpBarCurrent;
	
	private float offsetY;

    //script will be atached to each GameObject that can suffer dmg. 	
	void Start () {
            //put it on top of the character
		offsetY=gameObject.collider.bounds.size.y+5;
		Debug.Log(offsetY);
	}
	
	void Update () {
	}
	
	void OnGUI(){
            //the hp bar background location on screen
		Rect rcBg = new Rect(0,0,60,14);
            //the current HP bar 
		Rect rcCurrent = new Rect(0,0,((currentHp)/maxHp)*56,8);

            //the important part : where this object is located in my screen
		Vector3 point = mainCamera.WorldToScreenPoint(new Vector3(
                                                                           transform.position.x,
                                                                           transform.position.y+offsetY,
                                                                           transform.position.z)
                                                                          );
		
            //had to add the substraction since my Y axis were revesed (
            rcBg.y = Screen.height-point.y;  
   
            //do some ugly hardcoding so the bar is pretty and centered
   	 	rcBg.x = point.x-30;
		rcCurrent.x=rcBg.x+2;
		rcCurrent.y=rcBg.y+3;
		GUI.DrawTexture(rcBg,hpBarBG);
		GUI.DrawTexture(rcCurrent,hpBarCurrent);
	
	}
	
}

Any ideas on how can i remove this ‘not really centered hp bar’ behavior ?
P.S. i have tried using WorldToViewport() instead of WoldToScreen() , same result.
Thanks is advance and good luck @ coding

1 Answer

1

for posterity :