Gui Slider Math?

I’m just trying to make my frame follow the mouse, like a slider object. So basically my frame follows the mouse on the X axis, like this:

This is all my code is at the moment:

mouse.Move:connect(function()
    if down == true then
    	fr.Position = UDim2.new(0, mouse.X, fr.Position.Y.Scale,0)
    end
end)

I mean theoretically that should work but clearly I’m missing something. Help is appreciated because I suck when it comes to this stuff…

8 Likes

Could you show us a gif of what’s happening? why isn’t it working?

seeing your code, the slider isn’t constrained to the size of the container frame.

I click it and the object just disappears with a huge value on the X axis for offset. Presumably because I’m missing some formula with the math.

I could probably try clamping it now that I think about it though…

1 Like

Yeah, for my slider system using math.clamp on the X value works fine.

Try making it use scale instead of offset?

1 Like

You would definitely need some bounds for how far the slider would go. A simple math.clamp would be enough for this, but figuring out these bounds are hard, as well as the placing of the slider:

local originalPos = fr.Position
local slider = --slider gui

local padding = --number of pixels off the edges
local leftBound = padding
local rightBound = slider.AbsoluteSize.X - padding

mouse.Move:Connect(function()
	if down == true then
		fr.Position = UDim2.new(
			UDim.new(0, math.clamp(
				mouse.X - slider.AbsolutePosition.X,
				leftBound, rightBound
			)),
			originalPos.Y
		)
	end
end)

There is a very good chance that my math is off and it errors. Please document its behavior as clearly as possible if it is not intended!

19 Likes

Pretty sure the x property of the mouse is only for offset though. Not sure how I’d go about converting that to scale…

@posatta still no dice, it doesn’t behave properly.

@goldenstein64 Thanks for taking the time to write that! What exactly is the filler variable though? Is that like padding or…?

Yeah, exactly like padding!

For any future readers, the filler variable in my code was replaced with padding.

2 Likes

My guess is you have it inside some gui object that has its own nonzero X position, and you’re setting the position relative to the container. Subtract the position of the container from the mouse position.

1 Like

There is a constructor for UDim2 that allows for using two UDims as arguments, that being that new UDim at the beginning for X and originalPos.Y.

2 Likes

My bad, I misread originalPos.Y.

1 Like

Those will provide you with enough sample code

Although I have minor tips;

You’ll be dealing with AbsolutePosition and AbsoluteSize for Math stuff most of the time so use that instead of Offset and Scale also use events like InputBegan and such

8 Likes

Thanks again! It pretty much works, although it is a bit… seizure-inducing. Nothing some polishing up can’t fix. :slight_smile:

2 Likes