简体   繁体   中英

How to center health bar above enemy?

I have a working [sort of] health bar that displays when an enemy is pursuing you. The only problem is that it shows up, off centered, at the enemy's feet. I would like the bar to be centered above the enemy's head.

I have an idea of where the problem is, but no idea how to fix it.

public float maxHealth;
public float curHealth;

public Texture2D healthBar;

private float left;
private float top;

private Vector2 playerScreen;

public Fighter player;
public Mob target;
public float healthPercent;

void Start () 
{
    maxHealth = 10;
    curHealth = maxHealth;
}

void Update ()
{
    if(player.opponent != null) {
        target = player.opponent.GetComponent<Mob>();
        healthPercent = (float)target.health / (float)target.maxHealth;
    } else {
        target = null;
        healthPercent = 0;
    }
    playerScreen = Camera.main.WorldToScreenPoint(target.transform.position);
    left = playerScreen.x;                   //pretty sure right here
    top = (Screen.height - playerScreen.y);  //is the issue
}

void OnGUI()
{
    if (target != null) {
        GUI.DrawTexture(new Rect(left, top, (50 * healthPercent), 5), healthBar);
    }
}

WorldToScreenPoint gives you the WorldPoint where your model has its origin, i guess thats at its feet. So you want to add the height to it:

Vector3 healthBarWorldPosition = target.transform.position + new Vector3(0.0f, target.height, 0.0f);
healthBarScreenPosition = Camera.main.WorldToScreenPoint(healthBarWorldPosition);

where target.height is the height of the model(maybe a bit more)

This should give you the correct height. For the centered part:

left = playerScreen.x; 

says that the Rectangle has its left end at the center of your model. Thats why its off center. You have to substract halt the pixel size of your healthbar to have it centered.

private int healthBarWidth = 50;
private int healthBarHeight = 5;

...

left = healthBarScreenPosition.x - (healthBarWidth / 2);
top = healthBarScreenPosition.y + (healthBarHeight / 2);

The same holds true for the height, you just have to add instead of substract because ScreenPoints count from bottom to top and the Rect counts from top to bottom.

edit: ha, i guess i am your personal tutor today ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM