How to make a slider with bounds

so I found this script that allows me to make a slider that you can move from side to side but when you move the bar past where the slider ends it doesn’t stop.

local held = false

script.Parent.Button.MouseButton1Down:Connect(function()
	held = true
end)

script.Parent.Button.MouseButton1Up:Connect(function()
	held = false
end)

local UserInputService = game:GetService("UserInputService")

spawn(function()
	while wait() do
		if held == true then
			local MousePosition = UserInputService:GetMouseLocation()
			local ContainerPosition = script.Parent.Parent.AbsolutePosition
			local TracerPosition = script.Parent.AbsolutePosition
			script.Parent.Position = UDim2.new(0, MousePosition.X - ContainerPosition.X, -0.5, 0)
		end
	end
end)

how it is rn
image
how I want it
image

for the x value of the vector3, math.clamp(num, 0, 1) should work for you

https://create.roblox.com/docs/reference/engine/libraries/math#clamp

you dont really need a script to get started with sliders, try figure out https://create.roblox.com/docs/ui/ui-drag-detectors

Try this! :slight_smile:

local held = false

script.Parent.Button.MouseButton1Down:Connect(function()
	held = true
end)

script.Parent.Button.MouseButton1Up:Connect(function()
	held = false
end)

local UserInputService = game:GetService("UserInputService")

spawn(function()
	while task.wait() do
		if held == true then
			local MousePosition = UserInputService:GetMouseLocation()
			local ContainerPosition = script.Parent.Parent.AbsolutePosition
			local ContainerSize = script.Parent.Parent.AbsoluteSize
			local TracerPosition = script.Parent.AbsolutePosition
			local DragPosition = MousePosition.X - ContainerPosition.X

			script.Parent.Position = UDim2.new(0, math.clamp(DragPosition, 0, ContainerSize.X), 0.5, 0)
		end
	end
end)
1 Like

nice thanks this works perfectly.

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