How to limit a mousegrab to a certain range

I have a grab system that works for a specific part, but I wanna limit that parts movement.

		if mag < 9 then
			mover.Position = Vector3.new(ray.Origin.X, ray.Origin.Y)
		else 
			mover.Position = oripos
		end

Mag is magnitude, and oripos is an origin point I have. I don’t want to set the moving part to directly that position though, I just want to limit it within the magnitude from that position.

so is it like a click detector?

I figured out something that could work (I used Mouse for this, since I was just throwing it together quickly)

local LocalPlayer = game:GetService("Players").LocalPlayer
local Mouse = LocalPlayer:GetMouse()
local MaxDist = 10 -- This is Magnitude
local part2 = Instance.new("Part")
Mouse.TargetFilter = part2
local TestPart = workspace.TestPart
part2.Anchored = true
part2.Parent = workspace

Mouse.Move:Connect(function()
	local mousePos = Mouse.Hit.p
	if (TestPart.Position - mousePos).Magnitude > MaxDist then
		local cf = CFrame.lookAt(TestPart.Position,mousePos)
		part2.Position = TestPart.Position + cf.LookVector * MaxDist
		--Gets original position, finds lookvector between the two parts, and moves it to the max distance.
	else
		part2.Position = mousePos -- Passed check, put it in the mouse position
	end
end)

This isn’t particularly efficient, however.

Nope it’s just a part that goes to the Mouse.

I used Mouse, yeah, I’ll try this out.

local mousePos = mouse.Hit.Position.Unit * math.min(mouse.Hit.Pos.Magnitude, MaxDist)

You should also try using @DrKittyWaffles’s solution, it’s probably much more efficient since it doesn’t constantly construct new CFrames, and it looks much cleaner.