Hi guys how to get the closest player according to the mouse position

yo guys what’s good so basically I need to get the closest player at my mouse position

the mouse doesn’t need to be on the player

1 Like

pls help guys cmon pls help me
1

i need a simple example what am I supposed to do

Loop through every player and check the distance from your mouse.

--//Services
local Players = game:GetService("Players")

--//Variables
local LocalPlayer = Players.LocalPlayer
local Mouse = LocalPlayer:GetMouse()

--//Functions
local function FindClosestPlayer()
	local mousePosition = Mouse.Hit.Position
	
	local closestDistance = math.huge
	local closestPlayer = nil
	
	for i, player in ipairs(Players:GetPlayers()) do
		local HumanoidRootPart = player.Character and player.Character:FindFirstChild("HumanoidRootPart")
		
		if not HumanoidRootPart then
			continue
		end
		
		local distance = (HumanoidRootPart.Position - mousePosition).Magnitude
		
		if distance < closestDistance then
			closestDistance = distance
			closestPlayer = player
		end
	end
	
	return closestPlayer
end

task.wait(3)
print(FindClosestPlayer())
2 Likes

i tried but i didnt find the right formula, thanks anyways