Help with health bar math?

I feel kinda dumb, but I have no idea how this health bar is working in terms of the math. Between these two scripts. Anyone able to help explain?

  1. PlayerHealthBar script
[RequireComponent(typeof(RawImage))]
public class PlayerHealthBar : MonoBehaviour
{

    RawImage healthBarRawImage;
    Player player;

    // Use this for initialization
    void Start()
    {
        player = FindObjectOfType<Player>();
        healthBarRawImage = GetComponent<RawImage>();
    }

    // Update is called once per frame
    void Update()
    {
        float xValue = -(player.healthAsPercentage / 2f) - 0.5f;
        healthBarRawImage.uvRect = new Rect(xValue, 0f, 0.5f, 1f);
    }
}
  1. Player Script
public class Player : MonoBehaviour
{
    [SerializeField] float maxHealthPoints = 100f;

    float currentHealthPoints = 100f;


    public float healthAsPercentage
    {
        get
        {
            return currentHealthPoints / (float)maxHealthPoints;
        }
    }
}

@Rick_Davidson My maths are something to be desired

In Player, currentHealthPoints / maxHealthPoints returns a decimal value.
Let’s say player has 65 health, divided by his max possible health of 100, that’s .65, or 65%.

The Healthbar is taking that value, dividing it in half (Because the image is twice as long as the actual health bar), making it negative, and subtracting .5. As per our example, that means
-(.65 / 2) - .5 = -.825
That number is then used to set the X (horizontal) position of the healthbar image.
Let’s do the math again with 0 health left, 50, and 100:

0/100 = 0
-(0/2)-.5 = -.5 (At zero health, the health bar is moved half it’s length, showing only red)
50/100 = .5
-(.5/2)-.5 = -.75 (At half health, the bar will have moved 1/4 of the way to the right)
100/100 = 1
-(1/2)-.5 = -1 (At full health, the bar will be moved 1 unit to the left)

That’s what I understand, at least.

1 Like

Thank you very much!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms