How to fix NPC's Back and forth movement (pathfinding)

I’ve almost got my pathfinding script set up, there’s just one problem to face:

https://gyazo.com/4df4def25211152b77037655aaa59453

The movement is choppy, it keeps moving back and forth.
This is my code:

local AIPFS = game:GetService("PathfindingService")
local CS = game:GetService("CollectionService")

local Zombies = CS:GetTagged("Zombie")

local maxdist = math.huge

_G.Zombies = true

function ComputePath(From, To)
	local path = AIPFS:ComputeRawPathAsync(From,To, maxdist)
	
	local points = path:GetPointCoordinates()
	return points
end

function WalkTo(Hum, Point, Cancel)
	if Cancel then
		Hum:MoveTo(Hum.Parent.PrimaryPart)
	else
		Hum:MoveTo(Point)	
	end
end

function GetClosestPlr(From)
	local Closest, Distance = nil, math.huge
	
	for i, v in pairs(game.Players:GetChildren()) do
		local Dist = v:DistanceFromCharacter(From)
		
		if Dist <= Distance then
			Closest, Distance = v, Dist
		end
 	end
	
	if Closest then
		return Closest.Character
	else
		return nil
	end
end

while wait(0.2) do
	if _G.Zombies then
		for i, v in pairs(Zombies) do
			coroutine.wrap(function()
				local ClosestChar = GetClosestPlr(v.PrimaryPart.Position)
				
				if ClosestChar ~= nil then
					
					local pts = ComputePath(v.PrimaryPart.Position, ClosestChar:WaitForChild("HumanoidRootPart").Position)
					
					for i = 1, #pts do
						v:FindFirstChildWhichIsA("Humanoid"):MoveTo(pts[i])
						v:FindFirstChildWhichIsA("Humanoid").MoveToFinished:Wait()
					end
				end
			end)()
		end
	end
end
1 Like

This thread maybe similar to your error try it

1 Like

I tried what the other person worked, i found out it’s an issue with the coroutine. Since it’s constantly updating the new path it’s basically playing 2 paths at once in a way.

Fixed by doing the following:

I’ve gotten rid of

for i = 1, #pts do
	v:FindFirstChildWhichIsA("Humanoid"):MoveTo(pts[i])
	v:FindFirstChildWhichIsA("Humanoid").MoveToFinished:Wait()
end

And instead put:

if pts[3] then
							
	if pts[3].Action == Enum.PathWaypointAction.Jump then
		v:FindFirstChildWhichIsA("Humanoid").Jump = true
	end
							
	v:FindFirstChildWhichIsA("Humanoid"):MoveTo(pts[3].Position)
	v:FindFirstChildWhichIsA("Humanoid").MoveToFinished:Wait()
end

This makes it move constantly forward and if a new path is made it will switch to that one.

3 Likes

So you fixed it?

30char

1 Like

Yes, sorry forgot to mark it as a solution.