I need help making a pathfinding ai

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

  1. What do you want to achieve? Im trying to make a monster ai system that will chase the player using pathfinding

  2. What is the issue? the ai works flawlessly for the first 30 seconds then suddenly the movement starts stuttering then completely stops



local Pathfinding = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local path = Pathfinding:CreatePath({
	AgentHeight = 5;
	AgentRadius = 3;
	AgentCanJump = false;
	
	Cost = {
		Water = 100;
		DangerZone = math.huge
	}
})

local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection

local Character = script.Parent
local humanoid = Character:WaitForChild("Humanoid")


local function findTarget()
	local maxDistance = 250
	local nearestTarget
	
	for index, player in pairs(Players:GetPlayers()) do
		if player.Character then
			local target = player.Character
			local distance = (Character.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
			
			if distance < maxDistance then
				nearestTarget = target
				maxDistance = distance
			end
			
			if distance < 5 then
				nearestTarget.Humanoid.Health -= 100
			end
		end
	end
	
	return nearestTarget
end

local function followPath(destination)
	
	local success, errormessage = pcall(function()
		path:ComputeAsync(Character.PrimaryPart.Position, destination)
	end)
	
	if success and path.Status == Enum.PathStatus.Success then
		waypoints = path:GetWaypoints()
		
		blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
			if blockedWaypointIndex >= nextWaypointIndex then
				blockedConnection:Disconnect()
				followPath(destination)
			end
		end)
		
		if not reachedConnection then
			reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
				if reached and nextWaypointIndex < #waypoints then
					nextWaypointIndex += 1
					humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
				else
					reachedConnection:Disconnect()
					blockedConnection:Disconnect()
				end
			end)
		end
		
		nextWaypointIndex = 2
		humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
		humanoid.MoveToFinished:Wait()
	else
		
	end

end

while wait() do
	local target = findTarget()
	if target then
		followPath(target.HumanoidRootPart.Position)
	end
end
1 Like