Optimizations For My Pathfinding AI Module

Hi there!

I’ve been working on a module that makes enemy AIs a lot more easier to do. This is just for personal use, so I’m probably not gonna release it to the public. But anyways, it works like a charm and I haven’t encountered any problems so far.

But I wanna know, can I make my code better? If so, how? Also, I’m pretty new to metatables, self, __index, and other stuff like that, so there might be things that I should be doing but I’m not.

local ezpathfindingai = {}
local PS = game:GetService("Players")
local PTS = game:GetService("PathfindingService")
local RS = game:GetService("RunService")
ezpathfindingai.__index = ezpathfindingai

local function CheckHeight(HRP, target)
	if target then
		if math.abs(HRP.Position.Y - target.Y) < 3 then
			return true
		end
		return false
	end
end

local function RandomizePath(HRP, hum)
	local randomPos = Vector3.new(HRP.Position.X + math.random(-20, 20), HRP.Position.Y, HRP.Position.Z + math.random(-20, 20))

	hum:MoveTo(randomPos)
	hum.MoveToFinished:Wait()
end

local function FindPath(target, hum, HRP, attackRadius)
	if target then
		hum:MoveTo(target.Position)

		local isBlocked = false
		local path
		local success, errors = pcall(function()
			local pathParams = {
				["AgentHeight"] = 5.25,
				["AgentRadius"] = 5.25,
				["AgentCanJump"] = true
			}
			--path = PTS:CreatePath(pathParams)
			--path:ComputeAsync(HRP.Position, target.Position)
			
			path = PTS:FindPathAsync(HRP.Position, target.Position)
		end)

		if success then
			if path.Status == Enum.PathStatus.Success then
				for q,wp in ipairs(path:GetWaypoints()) do
					if q ~= 1 then					
						if wp.Action == Enum.PathWaypointAction.Jump then
							hum.Jump = true
						end
						if hum.Health <= 0 then
							break
						end
						if CheckHeight(HRP, wp.Position) == false then	
							warn("RECALCULATING PATH")
							FindPath()					
							break
						end
						
						hum:MoveTo(wp.Position)
						local check = hum.MoveToFinished:Wait(1)

						if not check then
							if hum.MoveDirection.Magnitude <= 0 then
								warn("RECALCULATING PATH")
								hum.Jump = true
								FindPath()
								break
							end
						end

						--local dot = Instance.new("Part")
						--dot.Parent = workspace
						--dot.Shape = "Ball"
						--dot.Position = wp.Position
						--dot.Anchored = true
						--dot.Size = Vector3.new(1,1,1)
						--dot.CanCollide = false
						--dot.Material = Enum.Material.Neon
						--dot.BrickColor = BrickColor.Red()
					end
				end
			else
				hum:MoveTo(target.Position - (HRP.CFrame.LookVector * 10))
			end
		else
			warn("ERROR WITH PATHFINDING: " .. errors)
		end
	end
end

local function FindTarget(distance, torso)
	local distance = distance

	for _,player in pairs(PS:GetPlayers()) do
		local pChar = player.Character

		if pChar then
			local pTorso = pChar:FindFirstChild("Torso")

			if pTorso then
				local magnitude = (torso.Position - pTorso.Position).Magnitude

				if magnitude < distance then
					distance = magnitude
					return pTorso
				else
					warn("NOT ENOUGH DISTANCE")
				end
			else
				warn("NO TORSO")
			end
		else
			warn("NO CHAR")
		end
	end
end

function ezpathfindingai.new(model, distance, attackRadius, attackFunction)
	local ai = {}
	setmetatable(ai, ezpathfindingai)

	ai.Humanoid = model.Humanoid
	ai.HRP = model.HumanoidRootPart
	ai.Torso = model.Torso
	ai.RenderDistance = distance
	ai.AttackRadius = attackRadius
	ai.AttackFunction = attackFunction

	return ai
end

function ezpathfindingai:StartAI()
	while true do
		local target = FindTarget(self.RenderDistance, self.Torso)

		if target then
			if (self.HRP.Position - target.Position).Magnitude <= 5 then
				self.AttackFunction(target)
			end
			
			self.HRP:SetNetworkOwner(nil)
			FindPath(target, self.Humanoid, self.HRP, self.AttackRadius)
		else
			self.HRP:SetNetworkOwner(nil)
			RandomizePath(self.HRP, self.Humanoid)
		end
	end

end

return ezpathfindingai

Pssst, that’s a bit harsh but alright.

What do ya mean by that? I am using pathfinding service in my module. Define “pathfinding system”.

Should probably include some sort of delay here to avoid freezing, unless one of those functions already has a delay in it that also affects the loop.

1 Like