Roblox Pathfinding + Optimizing Help

Hi, I’m making a zombie game on roblox and I’m relatively new to scripting. I’m using pathfinding to have zombies target players, but zombies sometimes have trouble finding the player/ going to the nearest waypoint. I’m wondering if there is something wrong with my code or if this is just normal for roblox’s pathfinding service. Also does anybody know a way to have all the zombie pathfinding at the same time in a non laggy way. Since my script does a for loop its slow from waiting for zombies to move.

Videos were not uploading so here are a few screen shots
Screen Shot 2022-07-31 at 12.42.04 PM

Screen Shot 2022-07-31 at 12.42.58 PM

Screen Shot 2022-07-31 at 12.43.29 PM

At all these points, the zombie got stuck in place

Here is my script

local PathfindingService = game:GetService("PathfindingService")
local manager = require(script.Parent.ZombieManager)

game.Players.PlayerAdded:Wait()

manager.Create("Zombie", CFrame.new(10,15,20))
manager.Create("ArmoredZombie", CFrame.new(-20,10,10))
manager.Create("Flamer", CFrame.new(20,10,10))

function FindClosestPlayer(pos)
	local character = nil
	local closestDistance = 10000000000
	local players = game.Players:GetChildren()
	for i=1, #players do
		local Character = players[i].Character or players[i].CharacterAdded:Wait()
		if (Character.PrimaryPart.Position - pos).Magnitude < closestDistance then
			closestDistance = (Character.PrimaryPart.Position - pos).Magnitude
			character = Character
		end
	end
	return character
end

while true do
	local zombies = workspace.ZombieFolder:GetChildren()
	if #zombies > 0 then
		for i,v in ipairs(zombies) do
			local follower = zombies[i]
			local Humanoid = follower.Humanoid
			local EndDestination = FindClosestPlayer(follower.PrimaryPart.Position)
			local path = PathfindingService:CreatePath()

			path:ComputeAsync(follower.HumanoidRootPart.Position, EndDestination.PrimaryPart.Position)
			if Humanoid.Health == 0 then
				follower:Destroy()
			else
				if path.Status == Enum.PathStatus.Success then

					local nodes = path:GetWaypoints()
					Humanoid:MoveTo(nodes[2].Position)
					wait()
				else
					warn("uh oh")
				end
			end
		end
	else
		wait()
	end
end

Thank you :smile:

the zombies doesn’t have to loop through every player per second, Instead you can make them search every 10 seconds or so.

Maybe detect if the zombie hasn’t moved in a while (zombirootpart.Velocity.Magnitude == 0) you can refresh its pathfinding (Move it randomly in a direction for a second and then continue)

1 Like

I’ll try this, Thank you for your help.

1 Like