I guess I gone a bit overkill with all the checks... whatever! here you have it! (haven't tested it so beware of typo's)
function nearestPlayer(player)
if player.Character then
local torso = player.Character:FindFirstChild("Torso")
if torso:IsA("BasePart") then
local position = torso.Position
local nearestDistance = math.huge
local nearestPlayer
for _, curPlayer in pairs(game.Players:GetPlayers()) do
if curPlayer ~= player and curPlayer.Character then
local curTorso = curPlayer.Character:FindFirstChild("Torso")
if curTorso:IsA("BasePart") then
local curDistance = (curTorso.Position - position).magnitude
if curDistance < nearestDistance then
nearestDistance = curDistance
nearestPlayer = curPlayer
end
end
end
end
return nearestPlayer
end
end
end |