- Home /
Why the healtbar is moving ?
I have this health bar script. Why, in the moment I move the camera, the healthbar moves with it instead of remaining over my spawned units. It works for gameobjects that are already in game, but has this problem for spawned units.
public class AIHealth : MonoBehaviour {
public Texture2D hpBarBG;
public Texture2D hpBarCurrent;
public Camera myCamera;
private float offsetY;
void Start () {
offsetY=gameObject.collider.bounds.size.y-2;
}
void Update () {
//I commented these 3 lines out when I tested it
//Removed the 2 line here, they are screwing things up
}
void OnGUI(){
Rect rcBg = new Rect(0,0,60,14);
health h=(health)GetComponent("health");
//Fixed this: added in the 1.0f to correct the calculation
Rect rcCurrent = new Rect(0,0,((h.currenthealth)*1.0f/h.maxhealth)*56,8);
//Just a simple clean up
Vector3 point = myCamera.WorldToScreenPoint(transform.position + Vector3.up * offsetY);
//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);
}
}
Comment
first off, what are you triying to implement? HealthBars above players, or a static player Health Bar that has to stay still?
Healthbar above unit. Just over their head. Like in RTS games. So the idea is when a unit move, the health bar follows it, no matter if I move the camera.
Your answer
Follow this Question
Related Questions
GUI healthbar 3 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Adding a floating health bar 2 Answers
Setting Scroll View Width GUILayout 1 Answer
Tracking Down GUI Errors 0 Answers