Hello. I’m doing AI for attacker NPC (NPC that will attack player).

My script will get all humanoids in distance and get the nearest one.
However when I move player or dummy it fails or it get wrong result.

local function FindPlayer(Distance)
local AllPlayersNearest = {}
for _,character in pairs(workspace:GetChildren()) do
local Found_Humanoid = character:FindFirstChildWhichIsA("Humanoid")
if Found_Humanoid ~= nil then
if Found_Humanoid ~= RakeHumanoid and (Found_Humanoid.RootPart.Position - RakeRootPart.Position).Magnitude <= Distance then
table.insert(AllPlayersNearest,Found_Humanoid)
end
end
end
function sort(t)
local sorted = {}
if #t > 1 then
for i = 2,#AllPlayersNearest do
local lastDistance = (t[i-1].RootPart.Position - RakeRootPart.Position).Magnitude
local checkDistance = (t[i].RootPart.Position - RakeRootPart.Position).Magnitude
if checkDistance < lastDistance then
table.insert(sorted,t[i])
end
end
sort(sorted)
else
sorted = t
end
return sorted
end
return sort(AllPlayersNearest)
end

I exactly don’t know where is problem.
Thanks for any help!

You should post the code for the actual movement of the AI as well. The sort function you’re using is completely useless because roblox has its own table.sort method.

An example of using the sort function with sorting humanoid distances:

local function getClosestPlayer(position)
local distances = {}
for _, player in pairs(game.Players:GetPlayers()) do
if player.Character then
table.insert(distances, {player, player:GetDistanceFromCharacter(position)})
end
end
if #distances > 0 then
table.sort(distances, function(a, b)
return b[2] > a[2]
end)
return distances[1][1]
end
end

What? That function uses the table.sort method to sort through a table of all players and their distances from a position to make the nearest player the first index, which is exactly the behavior you’re trying to achieve.