Health Bar UI Scripting

Hey there I have a health bar GUI and I want to script it. But the health bar is dropping from left to right instead of dropping from right to left. As it does in the roblox default one. How can I solve this issue?

local Players = game:GetService("Players")
local plr = Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local playergui = plr.PlayerGui
local maingui = playergui:WaitForChild("Main")
local general = maingui:WaitForChild("GeneralFrame")
local bars = general:WaitForChild("BarsFrame")
local healthbar = bars:WaitForChild("HpBar")

-- Initial settings
local initialPosition = healthbar.Position
local initialSize = healthbar.Size

local function updateHealthBar()
	local humanoid = char:FindFirstChild("Humanoid")
	if humanoid then
		local healthPercent = humanoid.Health / humanoid.MaxHealth
		local newSize = UDim2.new(initialSize.X.Scale * healthPercent, initialSize.X.Offset * healthPercent, initialSize.Y.Scale, initialSize.Y.Offset)
		local newPosition = UDim2.new(initialPosition.X.Scale + (initialSize.X.Scale - newSize.X.Scale) / 2, 0, initialPosition.Y.Scale, initialPosition.Y.Offset)

		healthbar.Size = newSize
		healthbar.Position = newPosition
	end
end

local function characterAdded(newChar)
	char = newChar
	local humanoid = char:WaitForChild("Humanoid")
	humanoid.HealthChanged:Connect(updateHealthBar)
	updateHealthBar()
end

plr.CharacterAdded:Connect(characterAdded)

if char then
	characterAdded(char)
end

Here is a visual example Watch 2024-08-01 10-25-05 | Streamable

set the bars anchorpoint to 1, 0.5 and the position to 1, 0, 0.5, 0

You can change the anchor point of the gui. So that when it decreases in size, it would keep staying on the left and not on the right. You don’t even need to script it.

The anchor point is already 0.5,0.5

if I do 1, 0.5 or 0.5, 1 it doesnt really change anything nor 0,0

Keep the anchor point. And remove this line that’s editing the position:

local newPosition = UDim2.new(initialPosition.X.Scale + (initialSize.X.Scale - newSize.X.Scale) / 2, 0, initialPosition.Y.Scale, initialPosition.Y.Offset)

Now it’s just scalling both ends… like the left side and the right side are scalling towards the middle. Not from right to left.