Finding closest humanoid to the player

Hello, i want to get the closest humanoid to the player, I’ve tried different things, example one of them below.
Any ideas?
I
I
V

function findNearest(player)
local start = player
for i,v in pairs(game.Workspace:GetChildren()) do
if(v:WaitForChild(“Humanoid”)) then
if(v ~= player) then
local h = game.Workspace.Baseplate.Position.X - v:WaitForChild(“Head”).Position.X
if(h < v:WaitForChild(“Head”).Position.X) then
return v.Name, v:WaitForChild(“Head”).Position
end
end
end
end
end

1 Like

I assume you’re including players and some kind of NPCs in this?

Firstly you’ll want to have your Humanoids all in one place - we can get player Characters from game.Players, but you’ll want to put all your NPCs under one directory like a folder in the workspace.

local npc_directory = game.Workspace['npc_folder'] --put the name of the folder here

local function ClosestHumanoid(player)
  local players = game.Players:GetPlayers();
  local npcs = npc_directory:GetChildren();
 
  local closest = { humanoid = false, distance = math.huge } --where we will store the closest humanoid found so far, along with how far away it is
  local character = player.Character or player.CharacterAdded:wait();
  local root = character:WaitForChild('HumanoidRootPart', 1);

  local to_check = npcs;
  for _,PLAYER in pairs(players) do
    if PLAYER.Character and PLAYER ~= player then
      table.insert(to_check, PLAYER.Character)
    end
  end

  for _,humanoid_model in pairs(to_check) do
    local displacement = (humanoid_model .HumanoidRootPart.Position - root.Position).magnitude;
    if displacement < closest.distance then
      closest.distance = displacement;
      closest.humanoid = humanoid_model:FindFirstChild('Humanoid');
    end
  end

  return closest.humanoid
end
3 Likes

yeah, that’s why im checking with a humanoid, and not in game.Players.
Anyways, im gonna check now ty.

1 Like

I would go for something like this:

local start = player
local pos = player.Character.HumanoidRootPart.Position
local values = {nil,10000} -- plr and distance
for i,v in ipairs(game.Players:GetChildren()) do
    if v ~= player then
         local distance = (v.Character.HumanoidRootPart.Position - pos).magnitude
        if distance < values[2] then
            values = {v,distance}
        end
    end
    if values[1] then
        return values
    else
        return nil
    end
end
3 Likes