0
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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);
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.