Help with positioning Slider Button

Hi everyone! I’ve been trying to implement a slider bar to control the music volume of my game, but for some reason the button element of the UI doesn’t position on my mouse, I can’t figure out why - hopefully someone can help me understand what I am doing wrong!

Here is the relevant code:

local Player = game:GetService("Players").LocalPlayer
local UIS = game:GetService("UserInputService")
local Runservice = game:GetService("RunService")

local Frame = script.Parent
local Button = script.Parent.Button

local db = false
local step = 0.01
local percentage = 0


function snap(number,factor)
	if factor == 0 then
		return number
	else
		return math.floor(number/factor+0.5)*factor
	end
end


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


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


Runservice.RenderStepped:Connect(function()
	if db then
		local MousePos = UIS:GetMouseLocation().Y
		local BtnPos = Button.Position
		local FrameSize = Frame.AbsoluteSize.Y
		local FramePos = Frame.AbsolutePosition.Y
		local pos = snap((MousePos - FramePos) / FrameSize, step)
		percentage = math.clamp(pos,0,1)
		Button.Position = UDim2.new(BtnPos.X.Scale, BtnPos.X.Offset, percentage, 0)
	end
end)

Here is my UI structure:
RobloxProblem1

I’m not sure if this will help, but you could use a DragDetector

Thank you for the reply! I’ve looked into DragDetector and it seems that it’s only for physical objects?

After hours of different approaches I found the culprit:

local MousePos = UIS:GetMouseLocation().Y

NEVER use this under any circumstances. It’s horrible.

Use this instead:

local MousePos = Player:GetMouse().Y

there’s nothing wrong using userinputservice. you just simply have to subtract the GUI inset that it applies to the mouse

local inset = game:GetService("GuiService"):GetGuiInset() 
local MousePos = (UIS:GetMouseLocation().Y - inset.Y)

(also, you could also enable IgnoreGuiInset on the screengui)

Hi Alex! Thank you for sharing, I had no idea about inset! I’ll set your reply as the solution, hope you are having a great weekend :slight_smile:

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