Enemy Pathfinding Help

Hello, I’m LuaGirlDeveloper and I’m working on a pathfinding Enemy, and I got into an issue because I’m trying to implement a random walk function or a patrol function but its looping in RunService and I can’t figure it out.

– Thank you.

Script AI:

--// Game Loaded
repeat
	task.wait(2.5)
until game.Loaded

--// Services
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")

--// Pathfinding Setup
local Path = PathfindingService:CreatePath({
	["AgentHeight"] = 7,
	["AgentRadius"] = 4,
	["AgentCanJump"] = false,
	["AgentCanClimb"] = false
})

--// Enemy Variables
local EnemyCharacter = Workspace.Figure
local EnemyHumanoid = EnemyCharacter:WaitForChild("Humanoid")
local EnemyPrimaryPart = EnemyCharacter.PrimaryPart
local EnemyAnimator = EnemyHumanoid:WaitForChild("Animator")

--// Initialize Enemy
EnemyPrimaryPart:SetNetworkOwner(nil)

--// Pathfinding Variables
local Waypoints
local NextWaypointIndex
local ReachedConnection
local BlockedConnection

--// Enemy Properties
local WalkSpeed = 10
local SprintSpeed = 25
local MaxSearchDistance = 200

--// Animations
local IdleAnimation = script.IdleAnimation
local WalkAnimation = script.WalkAnimation
local RunAnimation = script.RunAnimation

local CurrentAnimationTrack = nil
local FigureStatus = script.Status

--// Functions
local function PlayAnimation(Animation)
	if CurrentAnimationTrack then
		CurrentAnimationTrack:Stop()
		CurrentAnimationTrack = nil
	end
	
	CurrentAnimationTrack = EnemyAnimator:LoadAnimation(Animation)
	CurrentAnimationTrack:Play()
end

local function CanSeeTarget(Target)
	local EnemyToCharacter = (Target.Head.Position - EnemyCharacter.Head.Position).Unit
	local EnemyLook = EnemyCharacter.Head.CFrame.LookVector
	
	local DotProduct = EnemyToCharacter:Dot(EnemyLook)
	
	if DotProduct > 0.5 then
		return true
	else
		return false
	end
end

local function Attack(Target)
	local Humanoid = Target:FindFirstChild("Humanoid")
	
	if Humanoid then
		Humanoid:TakeDamage(100)
	end
end

local function FindTarget()
	local NearestTarget = nil
	local SearchDistance = MaxSearchDistance
	
	for Index, Player in pairs(Players:GetPlayers()) do
		local Character = Player.Character
		local Humanoid = Character:FindFirstChild("Humanoid")
		if Character and Humanoid and Humanoid.Health > 0 then
			local Distance = (EnemyPrimaryPart.Position - Character.PrimaryPart.Position).Magnitude
			if Distance < SearchDistance and CanSeeTarget(Character) then
				NearestTarget = Character
				SearchDistance = Distance
			end
			if Distance < 8 then
				Attack(Character)
			end
		end
	end
	return NearestTarget
end

local function FollowPath(Destination)
	local Success, ErrorMessage = pcall(function()
		Path:ComputeAsync(EnemyPrimaryPart.Position, Destination)
	end)
	
	if Success and Path.Status == Enum.PathStatus.Success then
		Waypoints = Path:GetWaypoints()
		
		if #Waypoints < 2 then
			EnemyHumanoid:MoveTo(Destination)
			if ReachedConnection then ReachedConnection:Disconnect() end
			if BlockedConnection then BlockedConnection:Disconnect() end
			return
		end
		
		BlockedConnection = Path.Blocked:Connect(function(BlockedWaypointIndex)
			if BlockedWaypointIndex >= NextWaypointIndex then
				BlockedConnection:Disconnect()
				FollowPath(Destination)
			end
		end)
		
		if not ReachedConnection then
			ReachedConnection = EnemyHumanoid.MoveToFinished:Connect(function(Reached)
				if Reached and NextWaypointIndex < #Waypoints then
					NextWaypointIndex += 1
					EnemyHumanoid:MoveTo(Waypoints[NextWaypointIndex].Position)
				else
					ReachedConnection:Disconnect()
					BlockedConnection:Disconnect()
				end
			end)
		end
		
		NextWaypointIndex = 2
		EnemyHumanoid:MoveTo(Waypoints[NextWaypointIndex].Position)
		FigureStatus.Value = "Walk" -- walk or run here
	else
		--warn(ErrorMessage)
	end
end

RunService.Heartbeat:Connect(function()
	local Target = FindTarget()
	
	if Target then
		FollowPath(Target.PrimaryPart.Position)
	else
		FigureStatus.Value = "Idle"
	end
end)

local LastStatus = ""

FigureStatus.Changed:Connect(function()
	if FigureStatus.Value == "Idle" and LastStatus ~= "Idle" then
		PlayAnimation(IdleAnimation)
		EnemyHumanoid.WalkSpeed = 0
	elseif FigureStatus.Value == "Walk" and LastStatus ~= "Walk" then
		PlayAnimation(WalkAnimation)
		EnemyHumanoid.WalkSpeed = WalkSpeed
	elseif FigureStatus.Value == "Run" and LastStatus ~= "Run" then
		PlayAnimation(RunAnimation)
		EnemyHumanoid.WalkSpeed = SprintSpeed
	end
	
	LastStatus = FigureStatus.Value
end)

First, I recommend putting a call to your function here:

if Target then
		FollowPath(Target.PrimaryPart.Position)
	else
		FigureStatus.Value = "Idle"
		--add something like Patrol()
	end

This “Patrol” function should move the enemy randomly, but it needs a cooldown so that it doesn’t spaz out.

local NextPatrolUpdate = 0 --at the top of the script
local PatrolTime = 5 --time it takes to move randomly again after moving once
function Patrol()
	if time() > NextPatrolUpdate then
		NextPatrolUpdate = time() + PatrolTime
		local RandomMovement = Vector3.new(math.random(-1, 1), math.random(0, 1), math.random(-1, 1)).Unit
		EnemyHumanoid:Move(RandomMovement)
	end
end

Okay I have one question if I’m making it a module should the find target be local or a module like Ai:FindTarget()
local maxdistance = self

or local function

If it’s a module, then yes, Ai:FindTarget() is more suitable, but you need a table like local Ai = {} and then at the end return Ai.

--@Ai
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")

local Ai = {}
Ai.__index = Ai

function Ai.new(Model : Model)
	local self = setmetatable({}, Ai)
	self.Model = Model
	self.Waypoints = nil
	self.NextWaypointIndex = nil
	self.ReachedConnection = nil
	self.BlockedConnection = nil
	return self
end

local function FindTarget(Model : Model, MaxSearchDistance : number)
	local NearestTarget = nil
	local SearchDistance = MaxSearchDistance
	
	
end

return Ai

Like this is the module that will be controlling the NPCs so I dont have to make like 6 scripts for 6 npcs

Yes, this is a lot better than cloning scripts for multiple NPCs.

This should be Ai:FindTarget(Model : Model, MaxSearchDistance : number)
but remember, you also have self so you might not need the Model.

function FindTarget(MaxSearchDistance : number)
	local Model = self.Model
	local NearestTarget = nil
	local SearchDistance = MaxSearchDistance
	
	
end

Yea, but one thing should I rewrite some of the movement code that already has patrol so its easer? then I can change it and update it later?

Yes, this is ideal, so you can separate the movement and patrol functions so they are independent.

should I still use the connections?

local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection

Probably, but I would recommend putting them into self.Connections like a table so that you can make an Ai:Destroy() that removes all of them all at once later.

Okay thank you for all your help.

This may be my last question but how would I include the connections into the new script or should I remove the connections?

@SubtotalAnt8185 I have a question about my module

They’ll be like

self.Connection.Blocked = Path.Blocked:Connect(function ...

Heres my script It errors but I’m not good at self:

--@Ai
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")

local Ai = {}
Ai.__index = Ai

function Ai.new(Model : Model)
	local self = setmetatable({}, Ai)
	self.Model = Model
	self.Connections = {
		Waypoints = nil,
		NextWaypointIndex = nil,
		ReachedConnection = nil,
		BlockedConnection = nil
	}
	self.Path = PathfindingService:CreatePath({
		["AgentHeight"] = 7,
		["AgentRadius"] = 4,
		["AgentCanJump"] = false,
		["AgentCanClimb"] = false
	})
	
	return self
end

function Ai:GetTarget(MaxSearchDistance : number)
	local NearestTarget = nil
	local SearchDistance =MaxSearchDistance
	
	for Index, Player in pairs(Players:GetPlayers()) do
		local Character = Player.Character
		if not Character then return end
		
		local Humanoid = Character:FindFirstChild("Humanoid")
		if not Humanoid then return end
		if Humanoid.Health < 0 then return end
		
		local Distance = (self.Model.PrimaryPart.Position - Character.PrimaryPart.Position).Magnitude
		
		if SearchDistance > Distance then
			NearestTarget = Character
			SearchDistance = Distance
		end
	end
	
	return NearestTarget
end

function Ai:Capture(Target)
	local Distance = (self.Model.PrimaryPart.Position - Target.PrimaryPart.Position).Magnitude
	
	if Distance > 3 then
		Ai:FollowPath(Target.PrimaryPart.Position)
	else
		Target.Humanoid:TakeDamage(100)
	end
end

function Ai:FollowPath(Destination : Vector3)
	local Success, ErrorMessage = pcall(function()
		self.Path:ComputeAsync(self.Model.PrimaryPart.Position, Destination)
	end)
	
	if Success and self.Path.Status == Enum.PathStatus.Success then
		self.Connections.Waypoints = self.Path:GetWaypoints()
		
		for Index, Waypoint in pairs(self.Connections.Waypoints) do
			local Target = Ai:GetTarget(200)
			
			if Target then
				Ai:Capture(Target)
				self.Model.Humanoid.WalkSpeed = 25
				break
			else
				self.Model.Humanoid.WalkSpeed = 10
				self.Model.Humanoid:MoveTo(Waypoint.Position)
				self.Model.Humanoid.MoveToFinished:Wait()
			end
		end
	else
		warn(ErrorMessage)
	end
end

function Ai:Patrol()
	local WayPoints = Workspace.Waypoints:GetChildren()
	local RandomWaypoint = math.random(1, #WayPoints)
	Ai:FollowPath(Workspace.Waypoints[RandomWaypoint].Position)
end

RunService.Heartbeat:Connect(function()
	Ai:Patrol()
end)

return Ai

Where is the error? Is it this?

This should probably be self:FollowPath

I did but i get this error: ReplicatedStorage.Ai:64: attempt to index nil with ‘HumanoidRootPart’

but I have a humanoidrootpart in the character

There is no HumanoidRootPart reference anywhere in the script.