Pathfinding Follower not working great

So, I tried making a NPC that follows you around with

:MoveTo()

But the problem was here that the NPC could get stuck, so I tried making a PathfindNPC but that didn’t work out well

Glitches
1 NPC would make random stop motion
2 NPC wouldn’t update players position it would go to the old one and then to the new one

so I was confused how to fix this and googled it like how it was gonna work out. But all the old Topics were outdated or not working. Mostof them had the same glitches as me.

CODE:

local PF = game:GetService("PathfindingService")
local Path = PF:CreatePath()
wait(5)
repeat wait() until #game.Workspace.Map:GetChildren() >= game.ReplicatedStorage.Amount.Value
local db = false
local NPC = script.Parent

function Move(torso)

	Path:ComputeAsync(NPC.Torso.Position,torso.Position)
	local P = Path:GetWaypoints()

	for v,i in pairs(P) do
		if i.Action == Enum.PathWaypointAction.Jump then
			NPC.Humanoid.Jump = true
		end
		NPC.Humanoid:MoveTo(i.Position)
		NPC.Humanoid.MoveToFinished:Wait(2)
	end
	NPC.Humanoid:MoveTo(torso.Position)

end

function getClosestPlayer()
	local closest_player, closest_distance = nil, 900000
	for i, player in pairs(workspace:GetChildren()) do
		if player:FindFirstChild("Humanoid") and player ~= NPC then
			local distance = (NPC.PrimaryPart.Position - player.PrimaryPart.Position).Magnitude
			if distance < closest_distance then
				closest_player = player
				closest_distance = distance
			end
		end
	end
	return closest_player, closest_distance
end

local car = false

while true do
	wait()
	if script.Parent.Humanoid.Health > 0 and script.Parent.Humanoid.PlatformStand == false then
		local player, distance = getClosestPlayer()
		
		if distance <= 45 and distance >= 5 then
			if player then
				Move(player.HumanoidRootPart)

			end
		else
			if player then
				Move(player.HumanoidRootPart)
				--script.Parent.Humanoid.WalkSpeed = 5
			else
				--script.Parent.Humanoid.WalkSpeed = 0
			end
			
		end
	end
end
1 Like