# Health bar - calculating health bar's position from percentage

I'm making a simple health bar in Unity 3D. Health bar UI is made from images. I'm having a problem with setting bar's position based on health percentage. Here's a script part:

    percentHealth = (currentHealth / maxHealth) * 100; //get's health percentage.

HealthBarHealth.transform.localPosition = new Vector3(healthBarCurrentX, 0); //moves health bar


I want healthBarCurrentX to be calculated from these values:

percentHealth - percentage calculated from max health and current. healthBarMaxX = 0f - health bar's position at 100% health. healthBarMinX = -273.5f - bar's position at 0% health.

So when health is 50%, currentX is at -136.65, etc.

Use Mathf.Lerp() to interpolate between the value you want at 0% and the value you want at 100%.

Mathf.Lerp

healthBarCurrentX = Mathf.Lerp(healthBarMinX, healthBarMaxX, currentHealth / maxHealth);


Why not use Slider component of uGUI? Its very easy,flexible and resolution independent.Check in, https://unity3d.com/learn/tutorials/projects/survival-shooter/player-health

You could have a black bar, with a green bar painted on top of it. Just change length of the bar on top, and it should work well.

blackbarlength = 100;
percentHealth = (currentHealth / maxHealth) * 100;
greenbarlength =  percenthealth;