Unable to get the actual position of the mouse

Hey there,
I am trying to make a circle particle appear on my GUI button whenever I click on the exact position of the mouse however the circle appears to be in the incorrect position

I also got help from this topic to convert the Vector3 into UDim2

How to convert Vector3 to UDim2?

This is how it looks:

Local script

local M = game.Players.LocalPlayer:GetMouse()
local particle = game.ReplicatedStorage.Particles.CicleParticle
local Cam = game.Workspace.CurrentCamera

function WorldToScreen(Pos)
	local point = Cam.CoordinateFrame:pointToObjectSpace(Pos)
	local aspectRatio = M.ViewSizeX / M.ViewSizeY
	local hfactor = math.tan(math.rad(Cam.FieldOfView) / 2)
	local wfactor = aspectRatio * hfactor

	local x = (point.x / point.z) / - wfactor
	local y = (point.y / point.z) /  hfactor

	return Vector2.new(M.ViewSizeX * (0.5 + 0.5 * x), M.ViewSizeY * (0.5 + 0.5 * y))
end

script.Parent.MouseButton1Click:Connect(function()

	local actualPosition = WorldToScreen(M.Hit.Position)

	local clonedParticle = particle:Clone()
	clonedParticle.Parent = script.Parent.Parent
	clonedParticle.Position = UDim2.new(0, actualPosition.X, 0, actualPosition.Y)
	wait(0.2)
	clonedParticle:Destroy()
end)

if u may or may not know the roblox mouse already has udim2 in it (sorta)

Mouse.X
-- and
Mouse.Y

both of these are offset values so you can do is

local pos = Udim2.fromOffset(Mouse.X,Mouse.Y)

and it would return the pos of the mouse! now its on u to convert it to a scale

//Side-Note
Nice Ui design btw

1 Like

Thank you so much! It worked

Also thanks again, that is my first UI design ever

well its pretty good for a first and your welcome :smiley:

1 Like
local players = game:GetService("Players")
local player = players.LocalPlayer
local mouse = player:GetMouse()
local camera = workspace.CurrentCamera

local viewportSize = camera.ViewportSize

mouse.Move:Connect(function()
	print(mouse.X / viewportSize.X)
	print((mouse.Y + 35) / viewportSize.Y)
end)

Bare in mind the legacy mouse object takes into account the GuiInset caused by Roblox’s top bar hence the addition of 35 to the mouse’s X position.

1 Like

mate the post has been solved.

and it would return the pos of the mouse! now its on u to convert it to a scale

My reply was to assist those that may not know how to do this & to shed some additional insight.

ok lol