Pathfinding npc twitching while updating path

Hello, so I’m making a pathfinding npc. The issue is that when it’s meant to switch paths it’ll twitch as you can see here

This is my code:

local function Move()
	Called = true
	local Target = GetTarget()
	if Target then
		local PrimePart = Target.PrimaryPart
		if PrimePart then
			local Path = PFS:CreatePath()
			Path:ComputeAsync(Torso.Position,PrimePart.Position)
			if Path.Status == Enum.PathStatus.Success then
				local Waypoints = Path:GetWaypoints()
				Called = false
				for i,v in pairs(Waypoints) do
					if Called == false then
						if v.Action == Enum.PathWaypointAction.Jump then
							Humanoid.Jump = true
						end
						Humanoid:MoveTo(v.Position)
						Humanoid.MoveToFinished:Wait()
					else
						break
					end
				end
			end
		end
	end
end
RunService.Stepped:Connect(Move)

can someone explain to me why this is happening and how I can fix it? Any help is appreciated!

I think the npc is going back to the old waypoint. Does anyone know how to fix?

You binded the move function to RunService.Stepped which will make the npc repathfind and try to go to the first waypoint of the new function. Your Called variable shouldn’t work because the new function is starting a new :MoveTo() while the old one isn’t cancelled because it is waiting for Humanoid.MoveToFinished:Wait(), causing the going back and forth thing.

1 Like

TY! But I have a question, how can I fix it? What edits do I have to do?

How do I stop the npc from going to old waypoints?

what does path.blocked do? just wondering

Ignore that, it’s not what you want

well what do I do then to fix the issue?

So you want to update the waypoints every frame, but only move to the next waypoint. Something like this where you calculate waypoints every frame and only move to the next one.

local PFS = game:GetService("PathfindingService")

local torso = game.Workspace.Dummy.Torso
local hum = game.Workspace.Dummy.Humanoid

game:GetService("RunService").Stepped:Connect(function()
	local target = game.Workspace.Part
	local path = PFS:CreatePath()
	path:ComputeAsync(torso.Position, target.Position)
	local waypoints = path:GetWaypoints()
	
	if waypoints and waypoints[2] then
		local data = waypoints[2]
		if data.Action == Enum.PathWaypointAction.Jump then
			hum.Jump = true
		end
		hum:MoveTo(data.Position)
	end
end)
3 Likes

thank you, i’ll try this give me a second

thank you, had a similar issue

1 Like

if waypoints and waypoints[2] then
local data = waypoints[2]
hum:MoveTo(data.Position)
end

Some how this single string of code managed to completely fix the twitching and inconsistency of my pathfinding script while allowing npcs to pathfind around objects. THANK YOU!

1 Like

RunService.Stepped works great! thanks, mate.