workspace.CurrentCamera.ViewportSize
-- Function:
local function getScreenSize()
return workspace.CurrentCamera.ViewportSize
end
This will return the size of the screen as a Vector2. Each time you call getRelativePos() you have to regenerate the ViewportSize, because this can change if you change your camera’s height.
Now get the mouse position:
local function getMousePos()
return Vector2.new(mouse.X, mouse.Y)
end
Now if we want to get the distance of the player’s mouse to the screen we can do 2 things.
Get the actual distance (If your screen is 2:1, x:y and you go to the top of y it will be 0.5 instead of 1)
Get the relative distance (Act like each screen is a 1:1)
Here Vector2.one/2 is the middle of the screen so 0.5, 0.5 in this case.
The distance will range depending on how far it is from the middle.
If you go straight up, left, right or down from the middle it should be exactly 1.
This is stiill not accurate, as the top would be about 1.3, while the bottom is 0.7. I want to get the mouse Y position accurately assuming the center is 0, the top is 1, and the bottom is -1.
Also, I just realised, your code gets the relative position and both x and y, I want it to return 1 (or -1, doesn’t matter, as long as I can differentiate top from bottom) only based on the Y axis. Thanks!
I had fun trying to figure this one out! No idea if there’s a better way but this is definitely a fine solution.
You can simply use this in a ScreenGui with IgnoreGuiInset enabled, no need for frame or any additional elements. You can attach and change it around to fit with any function/event you may have.
local IgnoreGuiInsetOffset = math.abs(script.Parent.AbsolutePosition.Y)
local MouseX = mouse.X
local MouseY = mouse.Y + IgnoreGuiInsetOffset -- This adjusts for Roblox's GuiInset
local AbsoluteX = script.Parent.AbsoluteSize.X
local AbsoluteY = script.Parent.AbsoluteSize.Y
local resultX = MouseX / AbsoluteX * 2 - 1
local resultY = 1 - MouseY / AbsoluteY * 2
print(resultX, resultY)
If you use camera viewportsize instead of a ScreenGui, you can grab TopbarInset equal to IgnoreGuiInset position difference from GuiService like this for the sake of the offset:
local GuiService = game:GetService('GuiService')
local IgnoreGuiInsetOffset = GuiService.TopbarInset.Height