Mouse's Vector2 To UDim2 Value

Hello fellow developers! Thank you for stopping by this post. So I’ve seen a few relevant posts regarding Vector2 and UDim2 values - and how they can be manipulated. I understand what Vectors are, as well as UDims, however I still am unable to figure this out (if possible). I wanted to display a GUI of my mouse’s location on my screen, so for example when the function is run:

local UIS = game:GetService("UserInputService")
local GUI = Player.PlayerGui.MouseGui
local function displayMouse()
    local Location = UIS:GetMouseLocation()
    GUI.Position = Location
end

Of course I know this does not work, since they are not of the same value types. So I was able to do this:

local UIS = game:GetService("UserInputService")
local GUI = Player.PlayerGui.MouseGui.Picture
local function displayMouse()
    local Location = UIS:GetMouseLocation()
    local Split = string.split(tostring(Location),",")
    local x = tonumber(Split[1])/800
    local y = tonumber(Split[2])/400
    local GUI.Position = UDim2.new(Split[1],x,Split[2],y)
end

I divided the values so that they would fit in the GUI. Now please don’t criticise any other errors I made in the script; I just retyped a rough draft of it out but it is certain that my main script works. The only problem is that it would look different, depending on different players’ resolutions. So my question is: Is there any way to have a GUI displayed accurately at the mouse’ location?

NOTE: While writing this post, I realised that I could offset the Vectors and get relatively accurate result, but it would still be nice if somebody could share a better solution (if there is one). Have a good day or night ahead!

You want to assign the GuiObject’s AbsolutePosition to the mouse’s position. You can do this as follows:

local function setAbsolutePosition(gui, position)
    local relativePosition = position - gui.Parent.AbsolutePosition
    gui.Position = UDim2.fromOffset(relativePosition.X, relativePosition.Y)
end

Position should be a Vector2, and gui should be the GuiObject you want to assign the AbsolutePosition of.

3 Likes

Worth adding to the above that you don’t need to convert your vector to a string and then split it, pass Location to the function shown above or use Location.X and Location.Y if you choose to implement it directly into your code.

2 Likes