How do I get the mouse's position relative to a ui?

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.

image

(more options is the thing I want to move)

image

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!

2 Likes

All UI Objects have a property named AbsolutePosition

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
1 Like

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.

1 Like
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)
1 Like

I kinda forgot about AbsolutePosition lol

anyways using some of the help from here and elsewhere I came up with this

button.MouseButton1Up:Connect(function(mousex, mousey)
    moreoptions.Position = UDim2.new(0, math.clamp(mousex, 0, background.AbsoluteSize.X - moreoptions.AbsoluteSize.X), 0 ,math.clamp(mousey, 0, background.AbsoluteSize.Y - moreoptions.AbsoluteSize.Y))
end)

and works exactly how I wanted it!

gets mouse position :white_check_mark:
moves UI to mouse position :white_check_mark:
clamps it so it doesn’t go offscreen :white_check_mark:

now I can continue working on my plugin :slight_smile:

3 Likes

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