How can I make a GUI element hover above a player?

Hi,

I want to make a health bar for enemies that hovers above there head. The actual health bar will be a box where the width value corresponds to the health, but how do I make a GUI element follow an object.

I should add this is a 2D game which should make it easier, I think!

thanks in advance!

Use Camera.WorldToScreenPoint

In the script for the health bar, create a variable for screen position like this:

var screenPos: Vector2;

You can then get the position of the object converted to screen coordinates with this:

screenPos = Camera.main.WorldToScreenPoint(gameObject.transform.position);

Now, you’re free to use this position in the placement of your bars (you can get the x and y coordinates simply from screenPos.x and screenPos.y). To actually put the bars on top of their heads, just add a number of pixels to the y placement to move it upwards on the screen. To actually make the bars follow the enemies you of course have to run the position converter repeadetly to update the screenPos variable, for example in Update().

Short warning though; I don’t think this is the cheapest operation to perform, so try not to run it every frame on every object if possible. Try to make it recalculate the position only when they move. But I’m not sure about that. Could work out just fine anyway :stuck_out_tongue: