Trying to calculate the shortest distance to a destination along a path?

Ive been working on a custom pathfinding system where basically there are breadcrumbs around the map along routes and NPCs will walk along these routes.

I am having trouble trying to calculate the shortest distance to the destination along the path, I think I am close.

	local ChosenSpawnpoint = NPCSpawnpoints:GetChildren()[math.random(1, #NPCSpawnpoints:GetChildren())]
	local ChosenDestination = NPCDestinations:GetChildren()[math.random(1, #NPCDestinations:GetChildren())]
	
	local PathsToChooseFrom = NPCPaths:GetChildren()
	local PreviousPath
	for Index, Object in ipairs(PathsToChooseFrom) do
		if PreviousPath == nil then
			PreviousPath = {Object, Index}
		else
			if (PreviousPath[1].Position - ChosenSpawnpoint.Position).Magnitude > (Object.Position - ChosenSpawnpoint.Position).Magnitude then
				PreviousPath = {Object, Index}
			end
		end
	end
	table.remove(PathsToChooseFrom, PreviousPath[2])
	
	PreviousPath[1].BrickColor = BrickColor.new("Bright blue")
	PreviousPath[1].Material = Enum.Material.Neon
	
	repeat
		local CurrentPath
		for Index, Object in ipairs(PathsToChooseFrom) do
			if CurrentPath == nil then
				CurrentPath = {Object, Index}
			else
				-- I think this is where I am messing up, everything else in my eyes should work perfectly fine. 
				if (CurrentPath[1].Position - PreviousPath[1].Position).Magnitude > (Object.Position - PreviousPath[1].Position).Magnitude and
					(CurrentPath[1].Position - ChosenDestination.Position).Magnitude > (Object.Position - ChosenDestination.Position).Magnitude then
					
					CurrentPath = {Object, Index}
				end
			end	
		end
		
		PreviousPath = CurrentPath
		table.remove(PathsToChooseFrom, PreviousPath[2])
		
		PreviousPath[1].BrickColor = BrickColor.new("Bright blue")
		PreviousPath[1].Material = Enum.Material.Neon
		
		wait(1)
	until
		#PathsToChooseFrom == 0

I commented in the middle where I think I am messing up. I am trying to determine if the current path part is the closest one to the previous position as well as the closest one to the destination. This way the NPC can make the correct turns at intersections.

Thank you and if you have any questions let me know!

I don’t mean to sound abrasive by any means, but I would advise against trying to reinvent the wheel.

Roblox already has PathfindingService which will help you a lot in this case

Yeah I agree with @overflowed, you should not be trying to reinvent the wheel of the pathfinding service because whatever you come up with will most likely be less efficient and most likely will not work properly.

I cant use there system for my use case. But its okay I have decided to write a plugin that will let me easily create nodes around the map and then use the Dijkstra method to determine the shortest route.