How can i make UI in SurfaceGUI Draggable?

I want to try to make these Popups draggable when you hold the title frame through the computer screen, but i’m not sure on how to start the custom Dragging function, as the Draggable property has been deprecated. How can i start and also restrict the position of the popup to the boundaries of the computer screen?

image

3 Likes

Basically:

local Frame = script.Parent
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

local Connection

Frame.InputBegan:Connect(function(i)
	if i.UserInputType == Enum.UserInputType.MouseButton1 then
		local offset = UserInputService:GetMouseLocation()-Frame.AbsolutePosition
		Connection = RunService.RenderStepped:Connect(function()
			local mousepos = UserInputService:GetMouseLocation() - Frame.Parent.AbsolutePosition - offset
			Frame.Position = UDim2.new(0,mousepos.X,0,mousepos.Y)
		end)
	end
end)

UserInputService.InputEnded:Connect(function(i)
	if i.UserInputType == Enum.UserInputType.MouseButton1 then
		if Connection then
			Connection:Disconnect()
		end
	end
end)

Information about the script:

  • First we assign a few variables/services etc.
  • Then we detect if there is input in our frame and see if that is of our mouse.
  • Then we get the current offset of our mouse from the anchorpoint of the frame so that the frame wont snap while dragging.
  • Then we take use of our Connection variable i.e a runservice connection from performance.
  • Then we take our mouse position relative to the frame’s parent. Because the frame moves relative to its parent.
  • Then we assign the position.
  • Then we need to later on disconnect our runservice when the mouse is no longer held.
2 Likes

Thanks, it works. But, is there a way to work with scale? the popup itself has the anchor point set to 0.5,0.5 so it appears in the center when created and the position of (from scale), 0.5,0.5. Will i need to simply set the AnchorPoint to 0,0 and set the position of popups to offset instead of scale? also, clamping should work for restricting the popup to the computer screen, right.

Nope

Mhm, just use math.clamp

Yes just divide the mouseposition by frame.Parent.AbsoluteSize

2 Likes

Thanks, it works! but, there is a slight offset to the popup, i assume because of the AnchorPoint. how can i fix it?

1 Like

Current code

	self.Instance.Title.InputBegan:Connect(function(input:InputObject)
		if input.UserInputType == Enum.UserInputType.MouseButton1 then
			local offset = UIS:GetMouseLocation() - self.Instance.AbsolutePosition
			 connection = Mouse.Move:Connect(function()
				local mousePos = UIS:GetMouseLocation() - Main.AbsolutePosition - offset
				local scaleMousePos = mousePos / Main.AbsoluteSize
				self.Instance.Position = UDim2.fromScale(scaleMousePos.X,scaleMousePos.Y)
			end)
		end
	end)
	
1 Like

Hm what do you mean by a slight offset?

1 Like

When holding the popup it moves to the side, even just clicking on it