AI not following path

So, i have this AI that is suppose to attack the player, and at the same time, find a way to get to said player without running into anything

But as shown in this picture. The AI creates a path to get to the player, but does not actually follow the path, and gets stuck at this table.

Why isn’t this working?

local PathfindingService = game:GetService("PathfindingService")
 
-- Variables for the zombie, its humanoid, and destination
local AI = script.Parent
local humanoid = AI:WaitForChild("Humanoid")
local HRP = AI:WaitForChild("HumanoidRootPart")

local Players = game:GetService("Players")
local Player


repeat
	wait()
	Player = Players:FindFirstChildOfClass("Player")
until Player

repeat
	wait()
until Player.Character

Debug = true

while true do
	wait()
	local destination = Player.Character:WaitForChild("HumanoidRootPart")
 
	-- Create the path object
	local path = PathfindingService:CreatePath()
	
	
	-- Compute the path
	path:ComputeAsync(HRP.Position, destination.Position)
	
	-- Get the path waypoints
	local waypoints = path:GetWaypoints()

	local waypoint2
	
	for _, waypoint in pairs(waypoints) do
		if Debug == true then
			local part = Instance.new("Part")
			part.Shape = "Ball"
			part.Material = "Neon"
			part.Size = Vector3.new(0.6, 0.6, 0.6)
			part.Position = waypoint.Position
			part.Anchored = true
			part.CanCollide = false
			part.Parent = game.Workspace
			wait()
		end
		waypoint2 = waypoint
	end
	destination = Player.Character:WaitForChild("HumanoidRootPart")
	if destination and waypoint2 then
		humanoid:MoveTo(waypoint2.Position)
	end
end

Some help would be greatly appreciated!

1 Like

Your Humanoid:MoveTo() function is outside of the loop meaning it will move to the last waypoint:

for _, waypoint in pairs(waypoints) do
		if Debug == true then
			local part = Instance.new("Part")
			part.Shape = "Ball"
			part.Material = "Neon"
			part.Size = Vector3.new(0.6, 0.6, 0.6)
			part.Position = waypoint.Position
			part.Anchored = true
			part.CanCollide = false
			part.Parent = game.Workspace
			wait()
		end
		humanoid:MoveTo(waypoint2.Position)
	end

also i don’t see the benefit of setting another waypoint outside of the loop

1 Like

Oh, thanks! But now I have a new issue. The AI nonstop goes back n forth to their old destination and their new one; Causing an endless loop.

You aren’t setting waypoint2 inside your loop. Just use the ‘waypoint’ instead. Also it might be worth adding a wait or it will iterate through the entire table almost immediately and make the NPC walk directly to the final destination again.