Find the closest part to the player's mouse

Hi, I want to achieve a system where you can move your mouse to any point of the screen, and if a part is on screen, it will print the closest part to your mouse.

I’m not too sure where to start, because I know how to find parts within a certain radius, but not the exact closest.

1 Like

Something like this:

function findClosestPart(mousePos, parts) -- mouse position, array of parts
    local closestPart = nil
    local closestDistance = math.huge
    for i, part in ipairs(parts) do
        local distance = (mousePos - part.Position).magnitude
        if distance < closestDistance then
            distance = closestDistance
            closestPart = part
        end
    end
    return closestPart
end

You can get the mouse position by mouse = player:GetMouse() with mouse.Hit

local Game = game
local Workspace = workspace
local RunService = Game:GetService("RunService")
local Players = Game:GetService("Players")
local Player = Players.LocalPlayer
local Mouse = Player:GetMouse()

local function OnRenderStep()
	local Position = Mouse.Hit.Position
	local Closest = {Part = nil, Distance = math.huge}
	for _, Part in ipairs(Workspace:GetDescendants()) do
		if not (Part:IsA("BasePart")) then continue end
		local Distance = (Part.Position - Position).Magnitude
		if Distance > Closest.Distance then continue end
		Closest.Part = Part
		Closest.Distance = Distance
	end
	print(Closest.Part.Name.." is "..Closest.Distance.." studs from the mouse.")
end

RunService.RenderStepped:Connect(OnRenderStep)

thanks this works :smiley: ill expand upon it