PathFinding NPC twitch when they update waypoint

when the NPC update the waypoint, they would keep twitching every time they update the waypoint.

I tried to use MoveToFinishEvent and tried to use less loop but it doesn’t work.

I am not sure what is the problem and I can’t find a similar problem as mine.

local root = script.Parent:WaitForChild("HumanoidRootPart")
	local rand = Random.new()
 

	    
	    
        
	       
	       
            


function Path()
    local players = game.Players:GetPlayers()
    local NearestZombie = players[1]

	local pRoot = NearestZombie.Character:WaitForChild("HumanoidRootPart")
  if NearestZombie.Character and NearestZombie.Character.Humanoid.Health > 0 then
	

    for i = 2, #players do
        local Distance1 = (NearestZombie.HumanoidRootPart.Position - pRoot.Position).Magnitude
        local Distance2 = (players[i].HumanoidRootPart.Position - pRoot.Position).Magnitude

        if Distance2 < Distance1 then
            NearestZombie = players[i]
        end
    end
end

	            local path = game:GetService("PathfindingService"):CreatePath({AgentRadius=6,AgentHeight=6})
	path:ComputeAsync(root.Position, pRoot.Position)
	            local points = path:GetWaypoints()
	 
	 for _, waypoint in pairs(points) do

    script.Parent:WaitForChild("Zombie"):MoveTo(waypoint.Position)
script.Parent:WaitForChild("Zombie").MoveToFinished:Wait()
    local distance
    repeat -- Wait until we are close to a point before moving to the next
          distance = (waypoint.Position - root.Position).magnitude

          script.Parent:WaitForChild("Zombie"):MoveTo(waypoint.Position)
script.Parent:WaitForChild("Zombie").MoveToFinished:Wait()
          wait()
    until distance < 100

end
end

	 
	-- The number inside wait will determine how long the zombie idles at
	-- the end of a path before starting to follow another player
	while wait() do
	    Path()
	
	end



1 Like

The problem you are having is a result of updating the current waypoint after the NPC has already reached the previous waypoint, causing a short delay in it’s movement. To fix this you would need to update the waypoint before the NPC reaches its current destination.

Using a combination of a loop and a magnitude calculation between the NPC’s current position and the waypoint can help you achieve this.

2 Likes

So is it like

while true do
distance1=(pRoot-waypoint.Position).magnitude

then Script.Parent.Humanoid:MoveTo(waypoint.Position)