Pathfinding zombie not creating paths fast enough

  1. What do you want to achieve?
    I want my ai zombie to stop in the middle of moving in a path and go to a moving target.
  2. What is the issue? Include screenshots / videos if possible!
    My ai does pathfind to the player, but whenever the player moves, the ai first finishes the original path first, then to the new position to the player. I don’t want this to happen. Instead, I want it to be able to pathfind a new course every second in the game to the new player, this is so the ai won’t turn so slow.
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I’ve tried editing the code and looking at it for errors. I’ve also tried looking at other tutorials to see if I did anything wrong, but none of it seems to be working. Any ideas on how I can fix this?
local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")
local CanAttack = true
local Damage = 20
local PathFindingService = game:GetService("PathfindingService")

function findNearestTorso(pos)
	local list = game.Workspace:children()
	local torso = nil
	local dist = 100000000
	local temp = nil
	local human = nil
	local temp2 = nil
	for x = 1, #list do
		temp2 = list[x]
		
		if (temp2.className == "Model") and (temp2 ~= script.Parent) and temp2.Name ~= script.Parent.Name 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


local function Attack(Torso)
	if CanAttack then
		CanAttack = false
		local humanoid = Torso.Parent:WaitForChild("Humanoid")
		humanoid.Health = humanoid.Health - Damage
		wait(1)
		CanAttack = true
	end
end

while true do
	local Target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
	if Target then
		local Newpath = PathFindingService:CreatePath()
		Newpath:ComputeAsync(script.Parent.HumanoidRootPart.Position,Target.Position)
		local Waypoints = Newpath:GetWaypoints()
		for i,v in (Waypoints) do
			script.Parent.Humanoid:MoveTo(v.Position)
			script.Parent.Humanoid.MoveToFinished:Wait()
		end
		script.Parent.Humanoid:MoveTo(Target.Position)
		local Distance = (script.Parent.HumanoidRootPart.Position - Target.Position).Magnitude
		
		if Distance <= 6 then
			Attack(Target)
		end
	end
task.wait()
end

Please let me know if there is a topic similar to this, or if I am in the wrong category. If the things you say are true, I will try to take down this post asap.

1 Like

You could print the starttime - time and print it to see how long it takes to get through every operation, and then try and debug from there.

1 Like