Size issue with healthbar

I want my healthbar’s size to scale properly with the amount of health the thing the player is mining currently has left.

The issue is that the healthbar starts at like 1/10 of the max health. The rest of the healthbar works but the size starts at the wrong value when I start mining something. The original size in studio is (1, 0, 1, 0) so it should start at the correct size.

This is my script:

local damageRM = game.ReplicatedStorage.Damage
local StartingTime = time()

local function updateBar(initialWidthScale, MaxHealth, bar, currentHealth)
bar.Parent.Visible = true
bar.Parent.TextLabel.Text = currentHealth … “/” … MaxHealth

local healthPercentage = currentHealth / MaxHealth
local newWidthScale = initialWidthScale * healthPercentage

local newSize = UDim2.new(newWidthScale, 0, bar.Size.Y.Scale, 0)
bar:TweenSize(newSize, Enum.EasingDirection.Out, Enum.EasingStyle.Linear, 0.3, false)

end

damageRM.OnClientEvent:Connect(function(MaxHealth, currentHealth, name)
script.Parent.BackgroundHealthbar.NameOfItem.Text = tostring(name)

StartingTime = time()

local initialWidthScale = script.Parent.BackgroundHealthbar.Size.X.Scale

updateBar(initialWidthScale, MaxHealth, script.Parent.BackgroundHealthbar.Healthbar, currentHealth)

if currentHealth <= 0 then
	script.Parent.BackgroundHealthbar.Visible = false
end

task.wait(2)

if time() - StartingTime > 2 then
	script.Parent.BackgroundHealthbar.Visible = false
end

end)

2 Likes

Shouldn’t the X-scale component simply be the ratio of current health to maximum health? It seems unnecessary to factor in the initial X-scale component.

1 Like

I recently switched from offset to scale and I forgot that scale calculates automatically with no need to account for the original width. Thanks for the solution.

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