How to update pathfinding?

Recently I’ve been trying to develop an AI system for my new game, but the AI wont constantly update its path like expected. Instead, It waits til it finishes its path and then moves to the next one. Anyone know whats up here?

local PathfindingService = game:GetService("PathfindingService")

local human = script.Parent:WaitForChild("Humanoid")
local torso = script.Parent:WaitForChild("UpperTorso")
local pathfinder = script.Parent

local offset = Vector3.new(0,0,0)
local path = PathfindingService:CreatePath()
path:ComputeAsync(torso.Position, game.Workspace.EndingPart.Position)
local waypoints = path:GetWaypoints()

spawn(function()
	while wait() do
		-- RIGHT RAYCAST
		local RRay = Ray.new(torso.Position, Vector3.new(0,0,1.5))
		local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(RRay, {torso, pathfinder.LowerTorso,pathfinder.RightLowerArm,pathfinder.RightUpperArm,pathfinder.LeftLowerArm,pathfinder.LeftUpperArm})
		if hit then
			print ("RIGHT - Player is to close to the RIGHT wall")
			
			offset = torso.CFrame.Position * CFrame.new(-1.5,0,0).Position
		else
			print ("SEARCHING FOR VALID WALL")
		end
	end
end)

spawn(function()
	while wait(1) do
		local path = PathfindingService:CreatePath()
		path:ComputeAsync(torso.Position, game.Workspace.EndingPart.Position)
		local waypoints = path:GetWaypoints()
	end
end)

for i, waypoint in pairs(waypoints) do
	if waypoint.Action == Enum.PathWaypointAction.Jump then
		human:ChangeState(Enum.HumanoidStateType.Jumping)
	end
	human:MoveTo(waypoint.Position + offset)
	human.MoveToFinished:Wait(2)
end

human:MoveTo(game.Workspace.EndingPart.Position)
1 Like

You can easily achieve the feature using my module. By calling the :Run() in the code, you are updating the previous path of the character.

Change this:
human.MoveToFinished:Wait(2)
to this
human.MoveToFinished:Wait()

Also, your spawned function is using it’s own local waypoints variable. Try removing the local under the spawn(function.. loop.