AI Problem. Weird behaviour

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
1 Like

Deleted my initial post because this is far better practice, mb.

Forgot about the sort method lmao

You don’t get it I need to get nearest player.

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.

No?? I don’t want get in the index I want get the nearest one for NPC

@Soliform’s function works, though they wrote DistanceFromCharacter as GetDistanceFromCharacter at line 6.

Also, I’m pretty sure for the position parameter you can just put the position of the NPC’s root part.

I figured out new function that is working without any problems.

Can you post your solution in case any other developer comes across a similar issue?