Review my draggable system

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

local viewPortSize = workspace.Camera.ViewportSize

local testFrame = script.Parent.Parent.Frame

local onPress = false

local function setOffsetToScale(offset: {x: number, y: number}): (number, number)
	return offset.x / viewPortSize.X, offset.y / viewPortSize.Y
end

local function setMousePositionInFrame(frame: Frame)
	local offset = {x = mouse.X, y = mouse.Y}
	local scaleX, scaleY = setOffsetToScale(offset)
	
	frame.Position = UDim2.new(scaleX, 0, scaleY, 0)
end

testFrame.InputBegan:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		if not onPress then onPress = true end
		
		repeat
			setMousePositionInFrame(testFrame)
			task.wait()
		until not onPress
	end
end)

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

I need your opinion!

1 Like

This script is great and will work without a problem, however I suggest you use RenderStepped instead of repeat until if you want smoother updating.

1 Like

Just send mouse.X and mouse.Y

This is a refactor of your code to adjust to best practices

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()

local viewPortSize = workspace.Camera.ViewportSize
local frame = script.Parent.Parent.Frame
local event: RBXScriptConnection

-- save memory!!!!!!!
local function setFrameToMousePosition()
	frame.Position = UDim2.fromScale(mouse.X / viewPortSize.X, mouse.Y / viewPortSize.Y)
end

testFrame.InputBegan:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		if event then return end
		event = RunService.RenderStepped:Connect(setFrameToMousePosition)
	end
end)

testFrame.InputEnded:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		if not event then return end
		event:Disconnect();
		event = nil
	end
end)

Variables defined inside loops will allocate memory for each iteration/frame, if you want to save memory, either initialize them outside with a type and initial value, then assign it a value inside the loop.

local x: number = 0
repeat
    x += 1
until x > 10
print(x)
2 Likes