Hello! I am working on an inventory system and I want to use a UIDragDetector and it is working fine but I want the object I am dragging to snap to the nearest frame in a collection. Here is an example:
(the two red dots should snap together and the mouse is over the element being dragged)
and this is my code that doesn’t work:
local drag:UIDragDetector = guiObj.UIDragDetector
drag:AddConstraintFunction(1, function(proposedPos:UDim2, proposedRot)
local posX = proposedPos.X.Offset
local posY = proposedPos.Y.Offset
for i,v in script.Parent.Inventory.Inventory:GetChildren() do
if not v:IsA("Frame") then continue end
local dist = (v.AbsolutePosition - guiObj.AbsolutePosition).Magnitude
if dist < 25 then
-- This makes the frame teleport away and my guess is due to reletivity
posX = v.AbsolutePosition.X
posY = v.AbsolutePosition.Y
break
end
end
return UDim2.fromOffset(posX, posY), proposedRot
end)
my drag detector settings:
Thanks for your help! (If anything needs more clarification or explaination don’t hesitate to ask)
Your current code is almost there, but it’s likely snapping incorrectly because AbsolutePosition is in screen coordinates while UDim2.fromOffset works in local GUI space. When you set posX = v.AbsolutePosition.X, you’re snapping it to screen space, which breaks the
layout.
Try converting the AbsolutePosition to local space first,
local localPos = guiObj.Parent:AbsoluteToLocal(v.AbsolutePosition)
posX = localPos.X
posY = localPos.Y
Then use UDim2.fromOffset(posX, posY) as you already are.
Let me know if your guiObj.Parent is not the immediate parent of the dragged object. It needs to be the GUI that controls its position for the snapping to align properly.
AbsoluteToLocal is not a valid member of Frame "Players.funfoxrr.PlayerGui.ScreenGui.InventoryGroup.InventoryContainer.Items"
The object is cloned and then set to the parent of a frame, is that a valid function…?
Ideally, both GUIs have identical anchor points, as these influence the interpretation of absolute position. You can calculate the translation otherwise.
Ideally, the dragging GUI object is a child of no other GUI object, as its position becomes relative. You can calculate the translation otherwise.