NPC stops several times

Hi people, I am trying to make an NPC that will chase you if you are in its range, the problem with this is that it gets stuck several times when chasing the player.

local Pathfinding = game:GetService("PathfindingService")
local NPCTorso = script.Parent.Torso
local Humanoid = script.Parent.Humanoid


function Follow()
		local path = Pathfinding:CreatePath(
		{ AgentCanJump = true,
		  AgentCanClimb = true
		}
)
	local distance= 50
	local waypoints

	for i, v in pairs(game.Workspace:GetChildren()) do
		local Hum = v:FindFirstChild("Humanoid")
		local Torso = v:FindFirstChild("Torso")

		if Hum and Torso and v ~= script.Parent and not v:FindFirstChildOfClass("IntValue") then
			if (NPCTorso.Position - Torso.Position).Magnitude <= distancia then
				Ruta = path:ComputeAsync(NPCTorso.Position, Torso.Position)
				
				local points = path:GetWaypoints()
				
				for i, part in pairs(points) do
					if part.Action == Enum.PathWaypointAction.Jump then
						Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
					end
					
					Humanoid:MoveTo(part.Position)
					Humanoid.MoveToFinished:Wait()
				end
			end
		end
	end
end

while task.wait(0.5) do
   Follow()
end

Video where the NPC gets stuck:

1 Like
local Pathfinding = game:GetService("PathfindingService")
local NPCTorso = script.Parent.Torso
local Humanoid = script.Parent.Humanoid


function Follow()
		local path = Pathfinding:CreatePath(
		{ AgentCanJump = true,
		  AgentCanClimb = true
		}
)
	local distance= 50
	local waypoints

	for i, v in pairs(game.Workspace:GetChildren()) do
		local Hum = v:FindFirstChild("Humanoid")
		local Torso = v:FindFirstChild("Torso")

		if Hum and Torso and v ~= script.Parent and not v:FindFirstChildOfClass("IntValue") then
			if (NPCTorso.Position - Torso.Position).Magnitude <= distancia then
				Ruta = path:ComputeAsync(NPCTorso.Position, Torso.Position)
				
				local points = path:GetWaypoints()
				
				for i, part in pairs(points) do
					if part.Action == Enum.PathWaypointAction.Jump then
						Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
					end
					
					Humanoid:MoveTo(part.Position)
				end
			end
		end
	end
end

while wait() do
   Follow()
end
2 Likes

Instead of using MoveToFinished:Wait(), you could probably use

repeat task.wait() until (Humanoid.Parent:GetPivot().Position - Part.Position).Magnitude < 2
1 Like

Wow, it worked, thank you very much.
Could you explain me your solution?

1 Like

waits are cringe, i removed them

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.