- Home /
How can I do health bar follows enemy?
Hi! I'm almost started to learning javascript and I'm doing exercises to get understanding of scripting. I'm trying to make a health bar following an enemy AI, but I don't know how to do it.
I'm not looking for someone how make the script for me, I just want someone try explain me how to do it because I tried so many times and I failed.
static var maxHealth : float = 100 ;
static var currentHealth : float;
var dmg : float;
var maxHealthtex : Texture2D;
var currentHealthtex : Texture2D;
var hpBarLenght : float;
var percentOfHp : float;
...
function Update () {
percentOfHp = currentHealth/maxHealth;
hpBarLenght = percentOfHp * 100;
}
function OnGUI() {
if (currentHealth > 0) {
GUI.DrawTexture(Rect(10, 10, hpBarLenght, 20), currentHealthtex);
}
}
I don't know how can I make GUI coordinates follows enemy.
Some suggestions?
Look for Bergzerg Arcade on youtube (I "think" Bergzerg was the guys name on there, been a few years since I watched it) .. He had a Hack'N'Slash tutorial on his youtube and I remember learning how to do this from him when I first started using unity.
Answer by Dazdingon · May 07, 2014 at 06:38 PM
Use : Camera.WorldToScreenPoint()
Get the on-screen position from the main camera
var targetObject : Transform;
var onScreenPosition : Vector3;
onScreenPosition = Camera.main.WorldToScreenPoint(targetObject.position);
Then display the health bar above the targetObject(the enemy)
var displayRect : Rect; displayRect = Rect(onScreenPosition.x - 50, Screen.height-(onScreenPosition.y + 45), 100, 20);
GUI.DrawTexture(displayRect, maxHealthtex);
displayRect.width = hpBarLenght;
GUI.DrawTexture(displayRect, currentHealthtex);
Your answer
Follow this Question
Related Questions
Healthbar above enemy : 2d 2 Answers
How to create Enemy Health Bar ? 4 Answers
Instantiate with healthbar dont work correctly 0 Answers
Health below zero but shows negative numbers 1 Answer
Unity health problem and enemy colision 3 Answers