How to make NPC follow a player using pathfinding?

So I’m creating an FPS zombies game and I’m having trouble with the zombie following a player. I’ve tried many ways but I always come back to this:

runService.Heartbeat:Connect(function(step)
	local path = pathFindingService:CreatePath()
	path:ComputeAsync(zombie.HumanoidRootPart.Position, target.Value.Position)
	
	if path.Status == Enum.PathStatus.Success then
		for _, waypoint in pairs(path:GetWaypoints()) do
			humanoid:MoveTo(waypoint.Position)
			humanoid.MoveToFinished:Wait()
		end
	end
end)

This is the closest to what I want but it still has many issues like zombie gets stuck or just stops, or it just starts going forwards and backwards.

There are so many questions about pathfinding on this forum that have already been solved and so many youtube videos, did you try searching up before posting this?

Don’t do pathfinding connected to a RunService event. You’re creating like 50 different paths a second for the zombie to follow.

What are you talking about?

This is a common way for people to make paths (specifically faster Paths for Mobs)?
They are really efficient for pathfinding

Yes i have, and i watched a video where he does this but he wrote like 100 lines of code, i want to see if there is an easier way to do it (also i have read other posts but in all of them the NPC firstly has to finish the created path then creates a new one)

Yea i figured that’s the problem, i need a way for NPC to stop following the old path and follow the new one. I also tried with while loop but then the zombie has to finish the first path and after that to create new path.

Here i tried creating a path every second but it makes zombies stop every second

local counter = 0

runService.Heartbeat:Connect(function(step)
	counter += step
	if counter >= 1 then
		counter = 0
		local path = pathFindingService:CreatePath()
		path:ComputeAsync(zombie.HumanoidRootPart.Position, target.Value.Position)
		
		if path.Status == Enum.PathStatus.Success then
			for _, waypoint in pairs(path:GetWaypoints()) do
				humanoid:MoveTo(waypoint.Position)
				humanoid.MoveToFinished:Wait()
			end
		end
	end
end)
1 Like