Npc not following correctly

Hi, im making a npc chase script with pathfinding, here is my code:

local soldier = script.Parent
local humanoid = soldier.Humanoid
local pathfindingservice = game:GetService("PathfindingService")

soldier.PrimaryPart:SetNetworkOwner(nil)

local function createPath(destination)
	local pathfindingservice = game:GetService("PathfindingService")
	local path = pathfindingservice:CreatePath()
	path:ComputeAsync(soldier.HumanoidRootPart.Position, destination.HumanoidRootPart.Position)
	for i, w in pairs(workspace.waypoints:GetChildren()) do
		w:Destroy()
	end
	for i, w in pairs(path:GetWaypoints()) do
		local waypoint = Instance.new("Part")
		waypoint.Position = w.Position
		waypoint.CanCollide = false
		waypoint.Parent = workspace.waypoints
		waypoint.Shape = "Ball"
		waypoint.Size = Vector3.new(1, 1, 1)
		waypoint.Anchored = true
	end
	
	return path
end

local function walkTo(destination)
	local path = createPath(destination)
	local waypoints = path:GetWaypoints() 
	for i, w in pairs(waypoints) do
		humanoid:MoveTo(w.Position)
		humanoid.MoveToFinished:Wait()

	end	
end

local function findTarget()
	local targets = workspace.RedTeamSoldiers:GetChildren()
	local maxDistance = math.huge
	local nearestTarget
	if not (targets == nil) then
		for i, t in pairs(targets) do
			local distance = (soldier.HumanoidRootPart.Position - t.HumanoidRootPart.Position).Magnitude
			if distance < maxDistance and t.Humanoid.Health > 0 then
				nearestTarget = t
			end
		end
	else	
		nearestTarget = nil
	end
	return nearestTarget
end


local function patrol()
	local target = findTarget()
	
	if target then
		walkTo(target)
	end
end

while true do
	patrol()
end

The code is working and there is no error, but npc following weird, here is the video: 2023-02-14 14-47-39

how do i fix this?

can someone help? i cant fix this :frowning:

Hi!
You should periodically update the path while the npc is moving.
I can highly recommend following along with these 2 videos: