How to get mouse position in Vector3

I want to be able to see which part is closer to the mouse using magnitude.
I have done this for a script by using mouse.Hit.p but that doesn’t work very well since if the part the mouse is on is far away or its the void it will get the distance from where the mouse is touching which doesn’t work very well. Here is an example of my code(structured building is a folder in workspace with parts inside)

local mousePos = mouse.Hit.p
local closestStructure

for i,v in pairs(game.Workspace.StructuredBuilding:GetChildren())do
	if closestStructure ~= nil then
		if (v.Position - mousePos).Magnitude < (closestStructure.Position - mousePos).Magnitude then
			closestStructure = v
		end
	else
		closestStructure = v
	end
end

does anyone have any better ways to do this?

1 Like

There is no better way, mouse.hit.p is not the object it is touching’s position, it’s just where the mouse position is in the 3d workspace.

Mouse | Roblox Creator Documentation <read through this again

And just add some invisible walls, that will make it less “buggy”.

(you’re defining the mouse’s position outside of the loop, maybe put it inside.)