Detect if mouse position is inside a frame

hello, im trying to detect weather the player mouse position is in a frame(over the frame). How would i do that?

1 Like

I think frames have an event called MouseEnter and MouseLeave. It might be called MouseHoverEnter or something similar.

local Frame = script.Parent
local Selected = false

Frame.MouseEnter:Connect(function()
  Selected = true
end)

Frame.MouseLeave:Connect(function()
  Selected = false
end)
1 Like

I need it as an if statement, if this isnt possible with an if statement is there any other way i can do that? Basically i need it for if the players mouse is over a gui

local Frame = script.Parent
local Selected = false

Frame.MouseEnter:Connect(function()
  Selected = true
end)

Frame.MouseLeave:Connect(function()
  Selected = false
end)

If Selected == true then

end

I love the effort lol! but unfortunatly i need it as just an if statement, no functions

this is actually the right way to do that

I never said it wasnt or was the right way. I need it as an if statement only. Maybe by getting the mouses position relative to the frames position?

There is nothing wrong with @9100ryan’s solution, but this is an alternative. Only issue is it does not fire unless you add a Mouse.Move event.

local Frame = script.Parent
local LocalPlayer = game.Players.LocalPlayer

local function Hovering()
	local MousePos = game:GetService("UserInputService"):GetMouseLocation() - game:GetService("GuiService"):GetGuiInset()
	local Guis = LocalPlayer:WaitForChild("PlayerGui"):GetGuiObjectsAtPosition(MousePos.X, MousePos.Y)
	
	for _, Gui in Guis do
		if Gui == Frame then
			return true
		end
	end
	return false
end

if Hovering() then
	-- do stuff
end
4 Likes

Like this:

if Mouse.X > Frame.AbsolutePosition.X and Mouse.X < Frame.AbsolutePosition.X + Frame.AbsoluteSize.X and Mouse.Y > Frame.AbsolutePosition.Y and Mouse.Y < Frame.AbsolutePosition.Y + Frame.AbsoluteSize.Y then

2 Likes

Yo big thx, this really helped me out.

No problem brother, I’ve found an even better way of doing it now as well if you want to try it out

table.find(PlayerGui:GetGuiObjectsAtPosition(Mouse.X, Mouse.Y), Frame)

I believe that is the code, playergui being the playergui inside of the local player, mouse being player:getmouse(), frame being the frame you want to verify

(EDIT): I just noticed it is the same as what Pragmatist suggested, but it is much more efficient to use table.find rather than an entire function looping through each one

3 Likes