How do I get the mouse’s position relative to a UI object?? like relative from the top left corner of the UI where the mouse is. I need this for my plugin so that when a user clicks on a button a frame appears at the position they clicked at in a UI just outside the button.
(more options is the thing I want to move)
I tried this script I found, but it didn’t work as well as I thought it would
local screenSize = camera.ViewportSize
local screenCenter = (screenSize * 0.5)
local mouse = --[[game:GetService("Players").LocalPlayer:GetMouse() --this is a plugin so I changed this]] plugin:GetMouse()
local function getRelativePos()
return (Vector2.new(mouse.X, mouse.Y) - screenCenter)
end
I’m going to guess it does work for use for getting the mouse in game, but doesn’t work for a plugin for some reason. if there’s an easy way to do this please let me know!
Are you looking for the mouse’s position from inside a DockWidgetPluginGui? It looks like it has a conveniently named GetRelativeMousePosition() method.
local widget = plugin:CreateDockWidgetPluginGui(...)
local guiMouseLocation = widget:GetRelativeMousePosition()
If you need that position relative to a frame, you can subtract the frame’s AbsolutePosition from it.
-- something like this...
local optsFrame = widget.Background.Frame.MoreOptions
local relativeLocation = guiMouseLocation - optsFrame.AbsolutePosition
The mouse’s position minus the position of the GUI should work. Make sure to use AbsolutePosition instead of Position, because this is a Vector2 instead of a UDim2. If you want it in offset instead of pixels, just divide the result by the AbsoluteSize of the GUI.
local UIS = game:GetService("UserInputService")
local UIObject = script.Parent -- for example
local MousePosition = UIS:GetMouseLocation() - Vector2.new(0, 36) -- use this if `ScreenGui` property `IgnoreGuiInset` is set to false
local MouseRelativePosition = Vector2.new(
UIObject.AbsolutePosition.X - MousePosition.X,
UIObject.AbsolutePosition.Y - MousePosition.Y
)
print(MouseRelativePosition.X, MouseRelativePosition.Y)