Why are the npcs not following correctly the waypoints?

local PathfindingService = game:GetService("PathfindingService")

local npcFolder = game.ReplicatedStorage:WaitForChild("NPCS")
local waypointsFolder = game.Workspace:WaitForChild("Waypoints")
local spawnInterval = 1

local function getRandomNPC()
	local npcs = npcFolder:GetChildren()
	return npcs[math.random(1, #npcs)]:Clone()
end

local function getRandomWaypoint()
	local waypoints = waypointsFolder:GetChildren()
	return waypoints[math.random(1, #waypoints)]
end

local function getSortedParts(waypoint)
	local parts = {}

	for _, part in ipairs(waypoint:GetChildren()) do
		if part:IsA("BasePart") then
			table.insert(parts, part)
		end
	end

	table.sort(parts, function(a, b)
		return tonumber(a.Name) < tonumber(b.Name)
	end)

	return parts
end

local function moveNPCUsingPathfinding(npc, targetPart)
	local humanoid = npc:FindFirstChild("Humanoid")
	local root = npc:FindFirstChild("HumanoidRootPart")

	if humanoid and root then
		local path = PathfindingService:CreatePath({
			AgentRadius = 2,
			AgentHeight = 5,
			AgentCanJump = false,
			AgentJumpHeight = 0,
			AgentMaxSlope = 45,
		})

		local targetPosition = Vector3.new(targetPart.Position.X, root.Position.Y, targetPart.Position.Z)
		path:ComputeAsync(root.Position, targetPosition)

		local waypoints = path:GetWaypoints()

		for i, waypoint in ipairs(waypoints) do
			humanoid:MoveTo(waypoint.Position)

			if waypoint.Action == Enum.PathWaypointAction.Jump then
				humanoid.Jump = true
			end

			humanoid.MoveToFinished:Wait()
		end
	end
end

local function cloneNPCToWaypoint()
	local npc = getRandomNPC()
	local waypoint = getRandomWaypoint()

	local sortedParts = getSortedParts(waypoint)
	if sortedParts[1] then
		local spawnPosition = sortedParts[1].Position + Vector3.new(0, 3, 0)
		npc:SetPrimaryPartCFrame(CFrame.new(spawnPosition))
		npc.Parent = game.Workspace

		wait(1)

		for _, part in ipairs(sortedParts) do
			moveNPCUsingPathfinding(npc, part)
		end
	else
		warn("No parts found in waypoint:", waypoint.Name)
	end
end

while true do
	cloneNPCToWaypoint()
	wait(spawnInterval)
end

Screenshot 2024-09-07 203655

1 Like

NVM i fixed the problem its not in the code

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