Finding if the mouse is within the bounds of a GUI object

Hello!

I have a script that detects that the mouse button 1 is down, as well as if the input started within the bounds of the label. The issue is that I’m not sure how to check if it’s within the bounds. I was thinking of using MouseEnter, but I’m not sure if I can because there are buttons above it, and therefore, I don’t think it would detect the mouse entering it.

Here’s what I have so far:

local UIS = game:GetService("UserInputService")
UIS.InputBegan:Connect(function(key)
	if key.UserInputType == Enum.UserInputType.MouseButton1 then
		local mouse = game.Players.LocalPlayer:GetMouse()
		local x = mouse.X
		local y = mouse.Y
		print(x,y)
	end
end)

TIA for the help! :smile:

The MouseEnter function would be quite useful for this particular task.

Well, that depends on where you’re signifying this script at.

2 Likes

math.clamp would be the answer into figuring out the bounds of the gui object.

1 Like

BasePlayerGui:GetGuiObjectsAtPosition returns a table of GuiObjects that are at the specified X and Y coordinates.

Since the PlayerGui class and StarterGui class inherit from the BasePlayerGui class, you can use it on the former (which is what you want)

So you would use it something like:

local gui_objects = player.PlayerGui:GetGuiObjectsAtPosition(x, y)

for _, gui_object in ipairs(gui_objects) do
    print(gui_object)
end
6 Likes

What do you mean by signifying where the script is? I should add that it’s basically a switch to turn off or on settings, and I kind of want the player to be able to “drag” the switch off or on, only if the input started within the switches’ bounds.

I will read up on that, thanks!

This could work, do you think it would cause some problems though, if it’s looping a lot? I could do some if statements to have it not execute but it’s still a concern for me. I will try this as well as the others’ suggestions.

I don’t think you will have thousands of GUIs on the screen in the same area where the mouse is.

1 Like

It is a simple loop and i’m sure it will not hamper peformance.

1 Like