Need help with zombie AI system

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

Im trying to make an optimized system that spawns zombies from a single script, while also handling their AI behavior (patrolling, checking for players, chasing, etc.) I am basically trying to make a minecraft zombie’s AI but not with a few things, for now (see bottom of post)

  1. What is the issue? Include screenshots / videos if possible!

I do not understand how to make the createPlayerPath.Create() and patrolModule.Patrol() functions mutually exclusive. Ive been have a few problems when play testing, like when the zombies are in the middle of patrolling they don’t immediately break away to start chasing the player, they finish their patrol first which isn’t what I want.

  1. What solutions have you tried so far? Did you look for solutions on the Creator Hub?

I’ve been looking on the DevForum, I asked ChatGPT and the studio AI Assistant for help, no luck though :frowning:

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

“ZombieHandler” script in ServerScriptService:

local PS = game:GetService("PathfindingService")
local RS = game:GetService("ReplicatedStorage")
local zombiesFolder = game.Workspace.ZombiesFolder

local spawnTime = 100
local maxRangeForPlayer = 35

local patrolModule = require(RS.ZombieModules.Patrol)
local createZombieModule = require(RS.ZombieModules.CreateZombie)
local findNearestPlayerModule = require(RS.ZombieModules.FindNearestPlayer)
local createPlayerPath = require(RS.ZombieModules.CreatePlayerPath)

while true do
	local clonedZombie = createZombieModule.Create() --this returns the zombie
	clonedZombie.PrimaryPart:SetNetworkOwner(nil)

	local patrolCoroutine = coroutine.create(function()
		while true do
			patrolModule.StartPatrol(clonedZombie)
			task.wait()
			--would i do yielding somewhere here? if so, how??
		end
	end)
	
	coroutine.resume(patrolCoroutine)

	task.spawn(function()
		while clonedZombie.PrimaryPart and clonedZombie.Humanoid.Health > 0 do
			local targetHRP = findNearestPlayerModule.Find(clonedZombie, maxRangeForPlayer) --this will return the players HRP if a player is found
			if targetHRP then
				while true do
					createPlayerPath.Create(clonedZombie, targetHRP)
					task.wait()
				end
			elseif targetHRP == nil then
				coroutine.resume(patrolCoroutine)
			end
			task.wait(0.5)
		end
	end)

	task.wait(spawnTime)
end

Notes:
-As of right now, I’m not working on making an attacking system for the zombies where they can damage you. I’m also not using raycasting right now so the zombies can see you through walls I guess.
-I didn’t include the modules because there’s like 4 of them and they’re long, but if you’d like to see them I will provide them.
-I basically just learned coroutines today so sorry if Im making dumb mistakes.
-This is my first post so please forgive me if I make any mistakes or anything.

3 Likes

Hi there @okwhatsupboi

I hope you are well.

I would approach this using OOP, here’s a video outlining it. It looks like you may be creating one in the zombie module already but just for simple ways I will demonstrate an example below:

local Zombie = {}
Zombie .__index = Zombie 

function Zombie.new(zombieModel)
	local zombie = {} 

setmetatable(zombie, Zombie) -- Find out more at https://create.roblox.com/docs/luau/metatables
return zombie
end

function Zombie:Patrol()
end

function Zombie:Chase()
end

return Zombie

Now you’ve got your class, you can require that ModuleScript in a Script on the server such as

local ZombieClassModule = require(pathtomodule)

...
-- Here you want to do logic 
local zombie = ZombieClassModule.new(...)

-- Can use methods such as 
zombie:Patrol()


In terms of chasing the Zombie, you’d want to use PathfindingService, and can use the MoveToFinish method in the examples. Note a limitation below:

Whilst using the Class.Humanoid.MoveToFinished|MoveToFinished event to detect when the character reaches each waypoint will work in most use cases, in larger games or games with numerous NPCs you may find less optimal performances and stuttering.

By default, each player’s Class.PlayerScripts contains a Class.ModuleScript named PlayerModule. Within PlayerModule, you will find another Class.ModuleScript called ClickToMoveController.

To determine when to move to the next obstacle, you should use the IsCurrentWaypointReached function provided by the ClickToMoveController module under Class.PlayerScripts.


In terms of making Patrol and Attack/Chase not mutually exclusive, you should just code it into the Zombie Class, let me know more and I will try to help here.

Thanks so much for your reply, I will be watching the video you provided shortly and ill get back to you if I have any more questions.

Okay so I’m a bit confused, I am currently trying to work on the zombie.Create() function but Im not sure how to go about setting the actual in-game zombie’s values. Like I understand setting them in a table, but how do I go about translating those values to the actual physical zombie? I also can’t really tell if I should return the normalZombie table or the physicalNormalZombie. Sorry, OOP is a little hard for me to understand, im still learning

Code:

local PS = game:GetService("PathfindingService")
local zombiesFolder = game.Workspace.ZombiesFolder
local storageZombie = game:GetService("ReplicatedStorage").Random.DefaultZombie

local zombie = {}
zombie.__index = zombie





function zombie.Create(walkSpeed)
	local normalZombie = {}
	normalZombie.WalkSpeed = walkSpeed
	
	local physicalNormalZombie = storageZombie:Clone()
	physicalNormalZombie.HumanoidRootPart.Position = Vector3.new(math.random(90, 110), 10, math.random(90, 110))
	physicalNormalZombie.Parent = zombiesFolder
	setmetatable(normalZombie, zombie)
	return normalZombie
end

Edit: Would it be as simple as doing

physicalNormalZombie.Humanoid.WalkSpeed = normalZombie.WalkSpeed

Or no?

Hello! If I was you I’d change the naming format of your script to make it less complex and to follow traditional OOP standards instead of using

function zombie.Create(walkSpeed)
	local normalZombie = {}
	normalZombie.WalkSpeed = walkSpeed
	
	local physicalNormalZombie = storageZombie:Clone()
	physicalNormalZombie.HumanoidRootPart.Position = Vector3.new(math.random(90, 110), 10, math.random(90, 110))
	physicalNormalZombie.Parent = zombiesFolder
	setmetatable(normalZombie, zombie)
	return normalZombie
end

You could instead do

function zombie.new(walkspeed : number)
local self = setmetatable({}, zombie)
self.WalkSpeed = walkspeed
return self

Then for the part where you clone the storage zombie and make it into a physical zombie you’d do that in a

function Zombie:Init()

You should return the NormalZombie, and then use whatever you use in Physical Zombie in an Initiate Function like so

local PS = game:GetService("PathfindingService")
local zombiesFolder = game.Workspace.ZombiesFolder
local storageZombie = game:GetService("ReplicatedStorage").Random.DefaultZombie

local zombie = {}


zombie.__index = zombie

export type zombie = {
	walkspeed : number
}





function zombie.Create(walkSpeed : number)
	local self = setmetatable({}, zombie)
	self.walkspeed = walkSpeed
	
	return self
end

function zombie:Init()
	local physicalNormalZombie = storageZombie:Clone()
	physicalNormalZombie.HumanoidRootPart.Position = Vector3.new(math.random(90, 110), 10, math.random(90, 110))
	physicalNormalZombie.Parent = zombiesFolder
end

To answer your final question, yes.

Thank you, this clears things up a bit. However, what exactly does this mean:

local self = setmetatable({}, zombie)

Im particularly confused on what the curly brackets mean. Also, why couldn’t you just use a colon instead of a period so you can access self more easily? Or does self mean something different in this case?

The curly brackets replace the normalZombie.

setmetatable(normalZombie, zombie)

and

setmetatable({}, zombie)

are the two same things.

The reason why we use a colon in OOP scripting is so that the script automatically references itself. Let’s say you wanted to put your metatable to the test and actually assign a value when you initate the script. In order to assign the value you made at zombie.new, you’d need to reference itself.

function zombie:Init()
local PhysicalNormalZombie = storageZombie:Clone()
physicalNormalZombie.HumanoidRootPart.Position = Vector3.new(math.random(90, 110), 10, math.random(90, 110))
physicalNormalZombie.Parent = zombieFolder
physicalNormalZombie.Humanoid.WalkSpeed = self.Walkspeed
end

Now since self.WalkSpeed was already defined in Zombie.New, the zombie would automatically get the walkspeed that you assigned for that class of zombies, and this is all possible by using the colon instead of the dot.

P.S when referencing this module script, you will need to also do

local zombie = require(zombiemodule)

local originalzombie = zombie.new(16)
originalzombie:Init()

for it to properly work.

Ok, thanks to both of you for helping me with this, I guess I’m fine on my own for now :smiley:

Alright, let me know if you ever need anymore help!

1 Like

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