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!