Draggable UI with bounds

Hiya devs, I have made a script that will allow for the user to drag a UI around the screen, however I dont want the user to drag it anywhere on the screen, I want the ui to stay on screen without a part of it going off the screen, but I have no idea how id do this, my script:

local UIS = game:GetService('UserInputService')
local frame = script.Parent

local dragToggle = nil
local dragSpeed = 0.25
local dragStart = nil
local startPos = nil

local function updateInput(input)
	local delta = input.Position - dragStart
	local position = UDim2.new(startPos.X.Scale, startPos.X.Offset + delta.X,
		startPos.Y.Scale, startPos.Y.Offset + delta.Y)
	game:GetService("TweenService"):Create(frame, TweenInfo.new(dragSpeed), {Position = position}):Play()
	
end

frame.InputBegan:Connect(function(input)
	if (input.UserInputType == Enum.UserInputType.MouseButton1) then
		print("Click")
		
		dragToggle = true
		dragStart = input.Position
		startPos = frame.Position
		input.Changed:Connect(function()
			if input.UserInputState == Enum.UserInputState.End then
				print("Release")
				dragToggle = false
			end
		end)
	end
end)

UIS.InputChanged:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseMovement then

		if dragToggle then
			print("Drag")
			updateInput(input)
		end
	end
end)

Use a clamping function, i.e; math.clamp when setting the GuiObject’s position.

local Workspace = workspace
local Camera = Workspace.CurrentCamera
local MouseLocation = UIS:GetMouseLocation()
local X = MouseLocation.X / Camera.ViewportSize.X
local Y = MouseLocation.Y / Camera.ViewportSize.Y
GuiObject.Position = UDim2.new(math.clamp(X, 0.25, 0.75), 0, math.clamp(Y, 0.25, 0.75), 0)
2 Likes