HealthBar for 5 Objects

Hello,

I am using the following script to display a healthbar for each object in my scene:

var soldier: Transform;
var healthbarwidth : int = 80;

function OnGUI() {
var screenPos : Vector3 = Camera.main.WorldToScreenPoint(soldier.position);
GUI.backgroundColor = Color.green;
GUI.Button(new Rect(screenPos.x - healthbarwidth/2, Screen.height - screenPos.y - 100, 80, 20),“Health”);
}

My Problem now:
As you can see I am referring to the Camera.main.WorldToScreenPoint of my object. It works fine but Unity displays each healthbar twice in the scene. In front of the camera and if I rotate the camera by 180 degrees there are the same healthbars again.

What’s the problem of my script?

Thanks for your help :slight_smile:

I don’t think there is anything wrong with your script. The problem is that in both cases there wordltoscreenpoint return the same location. These ease solution is to check if the direction towards your object from the cameras forward is less then 90.

soldiersDirection = (soldier.transform.position - camera.transform.position).normalized;
float angle = Vector3.Angle(camera.transform.forward, soldiersDirection);
if(angle > 90)
{
     // hide healthbar
}

That should help. Realize this is sent from my phone so there might be some typing errors.

I found a hint:

…and tried to improve my code:

var soldier: Transform;

var healthbarwidth : int = 50;

var heading = soldier.position - Camera.main.transform.position;

function OnGUI() {

var screenPos : Vector3 = Camera.main.WorldToScreenPoint(soldier.position);

if (Vector3.Dot(camera.transform.forward, heading > 0){

GUI.backgroundColor = Color.green;

GUI.Button(new Rect(screenPos.x - healthbarwidth/2, Screen.height - screenPos.y - 100, 50, 20),“Health”);

}

}

BUT it’s not working :frowning:

any idea?

var soldier: Transform;

var healthbarwidth : int = 80;

function OnGUI() {

var screenPos : Vector3 = Camera.main.WorldToScreenPoint(soldier.position);
var normScreenPos : Vector3 = soldier.position - transform.position;
normScreenPos = normScreenPos.normalized;
GUI.backgroundColor = Color.green;

if(Vector3.Dot(normScreenPos, transform.forward) > 0) //change value of greater to less than if needed
GUI.Button(new Rect(screenPos.x - healthbarwidth/2, Screen.height - screenPos.y - 100, 80, 20),"Health");

}