health bar not following enemy

Hi guys,

I am making a side scrolling game where the enemy and player moves along the Z axes and is able to move up and down on the Y axes.

My code below allows the health bar spawn at the enemy position.
the problem is if the enemy should move or spawn in a different location the health bar gets out of place

How can I fix this?

var redSpeed : Texture2D[] = new Texture2D[1];
var target : Transform;


function OnGUI()
{
	var screenPos : Vector3 = Camera.main.WorldToScreenPoint(target.transform.position);
	var enemyHealth = GetComponent("CharacterDamageEnemy");
	GUI.DrawTexture(Rect((screenPos.x),(screenPos.y),enemyHealth.hitPoints/1.5,5), redSpeed[0]);

}

function Update () {

	

}

What do you mean ‘out of place’? Where does the health bar go?

Where-ever it goes, one solution would be to position the health bar relative to the GameObject which has the health (as opposed to relating it to the camera and the target). If the camera is in view of the GameObject, it’ll show regardless.

Child the health bar to the enemy.

the health bar is a 2d texture. making it a child of the enemy won’t work.

well if you make it a child, regardless of what it is, texture2d or not, it will follow that enemy where ever he goes.

it didn’t follow the enemy. Thats the reason I used Camera.main.WorldToScreenPoint

Any object that is a child of another will move with its parent.
However, i just noticed younare using a gui, which complicates things.
Why not just use a game object?

I used GUI because I wanted the health bar to have a 2d look while the enemy is 2.5d

You can make a 2D looking object without GUI. Look at planes.

What do you mean it’s not following the enemy? What is happening instead? Where is the texture being drawn?

What you could do is have 2 planes, one a little closer to the camera than the other. The farther one would be the color of the background of your health bar, like red, while the closer one would be the color of the foreground of your health bar, such as green. You’d want to create these planes in a 3D modeling tool, as Unity’s planes have 100 vertexes and you only need 4. You should set up the planes so that the centerpoint of each plane is along one of the short edges. Then, parent the planes to your enemy and get them scaled correctly. You’ll need to write a script to scale the green plane by the health of the enemy. This is easy enough: have a variable, maxScale, which is the scale of the health bar along the major axis when your enemy is at full health. Then, every frame (or every time your enemy takes damage, if you want to be frugal with processing power) set the scale of the green plane along the major axis to maxScale * (currentHealthOfEnemy / maximumHealthOfEnemy).