Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Could someone explain why this health bar is acting weird? [SOLVED]

humanoid.HealthChanged:connect(function()
	local hp = humanoid.Health
	local hpd = hp / player.Character.Humanoid.MaxHealth
	local hpm = hpd * 200 <----------------------
	Healthnum.Text = math.floor(hp)
	Healthbar.Size = UDim2.new(0, hpm, 0, 25)
	Healthbar.BackgroundColor3 = Color3.new((maxhp - hp)/100, hp/235, hp/100)
	Healthbar.BorderColor3 = Color3.new((maxhp - hp)/100, hp/235, hp/100)
	Healthnum.TextStrokeColor3 = Color3.new((maxhp - hp)/100, hp/235, hp/100)
end)

SOLVE EDIT: was just a silly syntax mixup on my part :p

So I was dividing hp by maxhp so that my health bar would stay the same size no matter what your maxhp is, and it works. However, if the maxhp is anything but exactly 100, it'll be around 30 pixels smaller. Could anyone explain why that happens?

test

1 answer

You should not use offset for health bars as dividing the health by the max health will give you a value between 0 and 1, which can be used to just set the scale property of the Size.

You should use scale as no matter how large the max health is, it will always work correctly because health will never go over max health and it will always have a value between 0 and 1.


humanoid.HealthChanged:connect(function()
    local hp = humanoid.Health
    local hpd = hp / humanoid.MaxHealth --Using the humanoid variable since it's quicker.
    --No need for the hpm property.
    Healthnum.Text = math.floor(hp)
    Healthbar.Size = UDim2.new(hpd, 0, 0, 25) --hpd will always be a value between 0 and 1 as health can never be over MaxHealth.
    Healthbar.BackgroundColor3 = Color3.new((maxhp - hp)/100, hp/235, hp/100)
    Healthbar.BorderColor3 = Color3.new((maxhp - hp)/100, hp/235, hp/100)
    Healthnum.TextStrokeColor3 = Color3.new((maxhp - hp)/100, hp/235, hp/100)
end)

I hope my answer helped you. If it did, be sure to accept it.

3 comments

5

I'm hungry

0

^

0

^

This discussion is preserved as it was. New answers, comments, and votes are closed.