How do you specify the percentage of how far a button has been moved?

Hello developers,
I have a little math problem. As you can see in the video below, I have created a relocatable button. I would also like to specify the percentage by which it was moved. If the round button was moved all the way to the right, it is 100% and 0% if it was moved all the way to the left. Unfortunately the percentage does not show the actual percentage…


Here are the lines of code that govern everything:

local UserInputService = game:GetService("UserInputService")
local dragging = false
local SlideFrame = script.Parent.Parent
local Slider = script.Parent

Slider.MouseButton1Down:Connect(function()
	dragging = true
end)

UserInputService.InputEnded:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		dragging=false
	end
end)

UserInputService.InputChanged:Connect(function()
	if dragging then
		local MousePosition = UserInputService:GetMouseLocation() + Vector2.new(0, 36) 
		local relpos = MousePosition - SlideFrame.AbsolutePosition
		local Percent = relpos.X / SlideFrame.AbsoluteSize.X
		SlideFrame.Percent.Text = Percent
		Slider.Position = UDim2.new(math.clamp(Percent, 0, 1), 0, 0.5, 0)
	end
end)

Any help would be appreciated!

Try multiplying that number by 100 and maybe using math.floor on the display to make it look prettier. It looks to be working fine, but displaying a number between 0 and 1 instead of 0 and 100.

local Percent = math.floor((relpos.X / SlideFrame.AbsoluteSize.X) * 100)

Thank you for your reply! Your help did indeed work, but there is only one error. Since the button gets activated with a MouseButton1Down the text can go over 100 and under 0 (because, with my mouse, I can “slide” over the maximum size of the frame). Is there any way to fix this?

Perhaps keeping the percent line the same, but replacing the line that updates the display number.

local Percent = relpos.X / SlideFrame.AbsoluteSize.X
SlideFrame.Percent.Text = math.floor(Percent * 100)


sadly this didn’t work :confused:

I think using math.clamp to clamp the numbers would be your best option.

something like this?

SlideFrame.Percent.Text = math.clamp(PercentText.."%", 0, 100)

Yep. I don’t think putting the percent inside the math.clamp would play nice with data types and all that, though.

Thanks for your help, you made my day!

1 Like