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)