Health does not follow its Enemy

Hi,

I seem to not have understood something about unity.

I have a few enemies on screen, with health, but cant seem to get the health bars to follow the enemies.

Here is my code. It does not follow its target at all :frowning:

var target : Transform;//being the enemy
var health : Texture2D[] = new Texture2D[1];
var hitPoints : int = 100;


function OnGUI()
{
	var screenPos : Vector3 = target.position;
	
	GUI.DrawTexture(Rect((screenPos.x),(screenPos.y),hitPoints,7), health[0]);

}

I think that you are doing a mix with Screen Positions, and Scene Positions.

Take care whit that. On the GUI you need Screen coordinates. For example if your game’s window is 800 x 600, You have the corners (0,0), (0,600),(800,0), (800,600).
But in your scene for example you maybe have a floor made by a cube whose size in x axis is 100 and in y axis 100 too. Then u have a scene which can have the corners: (0,0), (0,100),(100,0), (100,100).

If the screen size isn’t equal to the scene size, the coordinates never can works.

I think you should use 3dText meshes that are objects that you can handle with Scene coordinates.
GUI is beauty but is not as easy as that.

Ok I will try text mesh and see.

You want to use WorldToScreenPoint() to get the pixel position x and y of the object.

As Afisicos said you are drawing the element with a vector representing world space. However, there is a handy method called WorldToScreenPoint.

private Vector3 screenPos;
void Update() 
{
     screenPos = Camera.main.WorldToScreenPoint(target.transform.position);
}

void OnGUI()
{
     GUI.DrawTexture(new Rect(screenPos.x, screenPos.y, .....and on and on);
}

Edit: Bah, typed it out too slow. :slight_smile:

I tried that. It is complaint that the enemy doesn’t have a camera. So I am afraid i can use that.

Use the camera in your scene. IE, Camera.main

I totally missed the Camera.main…

Thats what I was missing all along…

It should work now, Thanks alot.