So by following a few different tutorials, I was able to get a pretty decent script working that allows me to have floating HP bars above enemies in my game which scale with distance to the enemy (bigger @ closer range). The only problem is that, somewhow, the scaling causes the health bars to appear directly behind the player when the player is far enough away and is turned 180 degrees from the enemy. Here’s an example of what I mean:
These are the health bars floating above the enemies as intended.
These are the same health bars, if the player moves back a little bit and turns 180 degrees.
Here is the script I’m using for my floating health bars. The 3 textures are the 3 components of the health bar GUI object.
using UnityEngine;
using System.Collections;
public class FloatingHitPointBar : MonoBehaviour {
public Camera myCamera;
public Vector3 vec;
public float maxHealth = 100f;
public float currentHealth = 100f;
public Texture backgroundTexture;
public Texture foregroundTexture;
public Texture frameTexture;
public int fixedHealthWidth = 197;
float healthWidth;
public int healthHeight = 28;
public int healthMarginLeft = -28;
public int healthMarginTop = 25;
public int frameWidth = 266;
public int frameHeight = 65;
public float offsetY = 391.97f;
public float offsetX = 0.0f;
public float scale;
public float distance;
// Use this for initialization
void Start () {
myCamera = Camera.main;
}
// Update is called once per frame
void Update () {
if (currentHealth > maxHealth) {
currentHealth = maxHealth;
}
if (currentHealth < 0 ) {
currentHealth = 0;
}
healthWidth = fixedHealthWidth * (currentHealth/maxHealth);
distance = (myCamera.transform.position - transform.position).magnitude/1.5f;
}
void OnGUI(){
vec = myCamera.WorldToScreenPoint (transform.position);
GUI.DrawTexture(new Rect(vec.x-(frameWidth/2.0f)/distance,
Screen.height -(vec.y+offsetY/distance),
frameWidth/distance,
frameHeight/distance),
backgroundTexture, ScaleMode.ScaleToFit, true, 0 );
GUI.DrawTexture(new Rect(vec.x-(fixedHealthWidth/2.0f+healthMarginLeft)/distance,
Screen.height -(vec.y+offsetY/distance)+healthMarginTop/distance,
healthWidth/distance,
healthHeight/distance),
foregroundTexture, ScaleMode.ScaleAndCrop, true, 0 );
GUI.DrawTexture(new Rect(vec.x-(frameWidth/2.0f)/distance,
Screen.height -(vec.y+offsetY/distance),
frameWidth/distance,
frameHeight/distance),
frameTexture, ScaleMode.ScaleToFit, true, 0 );
}
}
Can anyone figure out what’s going on here?