Best Pathfinding Following AI

So I’m trying to make good pathfinding where it goes for the closet player and if theres no close player it starts to wonder around the map, E.G like the rake

local moveid = 0
moveid = moveid + 1
local id = moveid

script.Parent.HumanoidRootPart:SetNetworkOwner(nil)


function findTarget(pos)
	local list = game.Workspace:children()
	local dist = 150
	local temp = nil
	local temp2 = nil
	local human = nil
	local torso = nil
	for x = 1, #list do
		temp2 = list[x]
		if (temp2.className == "Model") and (temp2 ~= script.Parent) then
			temp = temp2:findFirstChild("HumanoidRootPart")
			human = temp2:findFirstChild("Humanoid")
			if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
				if (temp.Position - pos).magnitude < dist then
					torso = temp
					dist = (temp.Position - pos).magnitude
				end
			end
		end
	end
	return torso
end

while wait() do
	local target = findTarget(script.Parent.HumanoidRootPart.Position)
	if target then
		local path = game:GetService("PathfindingService"):FindPathAsync(script.Parent.HumanoidRootPart.Position, target.CFrame.p)
		if path.Status == Enum.PathStatus.Success then
			
			local waypoints = path:GetWaypoints()
			for i = 2, #waypoints do
				if id ~= moveid then break end
				local waypoint = waypoints[i]
				local destination = waypoint.Position
				script.Parent.Humanoid:MoveTo(destination)
				local connection;
				if waypoint.Action == Enum.PathWaypointAction.Jump then
					script.Parent.Humanoid.Jump = true
					connection = script.Parent.Humanoid.Changed:Connect(function()
						script.Parent.Humanoid.Jump = true
					end)
				end
				local reached = script.Parent.Humanoid.MoveToFinished:Wait()
				if connection then
					connection:Disconnect()
				end
				if not reached then
					break
				end
			end
		else
			script.Parent.Humanoid:MoveTo(script.Parent.HumanoidRootPart.CFrame * Vector3.new(0, 0, 2))
			script.Parent.Humanoid.MoveToFinished:Wait()
			

		end
	end
end

Okay, but what is the problem?

Its very buggy when walking :confused:

Do you have any video showing that?


Heres a small clip of what I mean

I’m pretty sure this is to be expected, since pathfinding takes time to go to player location, the NPC would go to the old position, the player would be moving then the NPC would stop for a bit, then calculate.

This is why some games implement custom AI using A* algorithm.

OOF, so if I wanted to fix it I would have to use custom AI

Well to make it better, you can make the NPC go faster. If you’re looking for a perfect AI, you either have to make your own AI or just use magnitude, with magnitude there will be a problem, which is your AI can’t go around obstacles.