UI Collision Detection

How do I detect if one GUIObject is touching another?

I’m not expecting a script to be written for me, but, I just need some advice on how I should do this.

Thanks ahead of time!

1 Like

You can get the absolute positions and sizes of both and do some math to calculate if they intersect on the x and y both, if so, they’re touching.

You should read this:

1 Like

Here is a function I wrote for you. Just put the params in:

function isTouching(guiObject1, guiObject2)
    local pos1 = guiObject1.AbsolutePosition
    local size1 = guiObject1.AbsoluteSize
    local pos2 = guiObject2.AbsolutePosition
    local size2 = guiObject2.AbsoluteSize

    local x1, y1, x2, y2 = pos1.X, pos1.Y, pos1.X + size1.X, pos1.Y + size1.Y
    local x3, y3, x4, y4 = pos2.X, pos2.Y, pos2.X + size2.X, pos2.Y + size2.Y

    if x2 < x3 or x1 > x4 or y2 < y3 or y1 > y4 then
        -- They are not overlapping
        return false
    else
        -- They are overlapping
        return true
    end
end

Please let me know if it worked or not :slight_smile:

1 Like

@nicknickphoenix I will test your function out soon, thanks for the reply. @Hqsuperlabgames Your reply was also incredible helpful.
However, I wrote my own, with some inspiration from many Devforum posts.

local function detectGUIOverlap(object1, object2)
	local result = false
	local objectsAtPosition = game.Players.LocalPlayer.PlayerGui:GetGuiObjectsAtPosition(object1.AbsolutePosition.X, object1.AbsolutePosition.Y)
	for i,v in pairs(objectsAtPosition) do
		if(v.Name == object2.Name) then
			result = true
		end
	end
	return result
end
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.