How can I improve my path finding zombies?

I have made a zombie pathfinding ai but it is quite stupid and sometimes it just slams itself into a object


local zombie = script.Parent
local pathfindingService = game:GetService("PathfindingService")

local target -- This will store the target player for the zombie to chase
local attackRange = 8 -- Adjust this value to control the range at which the zombie attacks the player
local attackDamage = 0.1 -- Adjust this value to set the damage dealt to the player

local walkanim = script:WaitForChild("walk")
local hum2 = script.Parent:WaitForChild("Humanoid")
local walk = hum2:LoadAnimation(walkanim)
walk:Play()
walk.Looped = true


local function findNearestPlayer()
	local players = game.Players:GetPlayers()
	local closestDistance = math.huge

	for _, player in ipairs(players) do
		if player ~= game.Players.LocalPlayer and player.Character and player.Character:FindFirstChild("Humanoid") and player.Character.Humanoid.Health > 0 then
			local distance = (player.Character.HumanoidRootPart.Position - zombie.HumanoidRootPart.Position).magnitude
			if distance <= closestDistance then
				closestDistance = distance
				target = player.Character.HumanoidRootPart
				return target
			end
		end
	end
end
local humanoid = zombie.Humanoid

while humanoid.Health ~= 0 do


	local target = findNearestPlayer()

	if target then

		local distanceToTarget = (target.Position - zombie.HumanoidRootPart.Position).magnitude
		if distanceToTarget > attackRange then
			-- Chase the player
			humanoid:MoveTo(target.Position)
			humanoid.MoveToFinished:Wait()
		else
			-- Attack the player
			target.Parent.Humanoid:TakeDamage(attackDamage)
		end
	end
	task.wait()
end



local zb = workspace.Sounds.zb






if humanoid.Health == 0 then
	local soundtable = zb:GetChildren()
	
	local soundindex = math.random(1,#soundtable)
	
	local randomsound = soundtable[soundindex]
	
	randomsound:Play()
	zombie:Destroy()
end



zombie.Humanoid.HealthChanged:Connect(function(health)
	
end)
2 Likes
1 Like

I saw it but I’m wondering if I’m able to make the goal to be the player?

yes - this doesnt give an example of player but all it needs is a base part and has getnearestcharacter as a function
SimplePath Example.rbxl (45.8 KB)

But How would I put the base part inside the player?

Just think of a basepart as a part, you can use the humanoidrootpart, the head, the left arm anything.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.