local module = {}
module.nodefold = nil
function module.updatefold(fold)
module.nodefold = fold
for _,v in fold:GetChildren() do
if v:IsA("Part") and v:FindFirstChild("NConnector") then
else
error(v:IsA("Part") and "A node has no connections" or "A node is not a part!")
end
end
end
local function grabdist(part,goal)
return (part.Position - goal.Position).Magnitude
end
function module.pathAstar(start,finish)
local open = {{start,grabdist(start,finish),0,nil}} -- starts with the distance as a base so node, distance from end, traveled ,origin node so it is node,fcost,heretcost,origin
local closed = {} -- already done nodes {node,cost,originates}
local goalreached = false
repeat
table.sort(open, function(a,b)
return a[2] < b[2]
end)
local nodeinfo = open[1] -- opens the first node, which is the cheapest after sorting.
if nodeinfo[1] == finish then -- node info is currently the cheaper than everything else, and is the goal, so it must be the most effecient path.
goalreached = nodeinfo[1]
end
for _,v in nodeinfo[1]:GetChildren() do -- all connections in node
if v.Name == "NConnector" then
local tf = false
local newnodeobj = v.Value -- the next node instance.
for _,a in closed do
if a[1] == newnodeobj then
tf = true -- marks as "In the closed"
end
end
if not tf then -- skips if in the closed, closed nodes should not be re-expanded because if the new path that was just opened took longer (thus being more expensive than the original path taken to reach that point.)
local heretdist = grabdist(newnodeobj,nodeinfo[1])+nodeinfo[3] -- grabs dist between new node and old node, and adds the already traveled distance
local cost = heretdist+grabdist(newnodeobj,finish) -- adds total traveled + total distance to finish
local newnodeinfo = {newnodeobj,cost,heretdist,nodeinfo} -- sets up table
for i,a in open do -- checks all already opened things
if a[1] == newnodeobj then -- a is a node table, so a[1] is the node object. newnodeobj is a node object (a part.)
if heretdist < a[3] then -- compares this distance, to the old distance and lets the cheaper one override. fcost is already calculated.
open[i] = newnodeinfo -- if optimal replaces
tf = true
end
end
end
if not tf then -- if not replaced adds.
table.insert(open,newnodeinfo) -- adds it to open nodes
end
end
end
end
table.insert(closed,nodeinfo)
table.remove(open,1)
until goalreached or #open == 0
if not goalreached then
error("Could not locate end node!")
return nil
else
local path = {}
local cur = goalreached
while cur[1] ~= start do
table.insert(path,cur[1])
cur = cur[4]
end
for i = 1, math.floor(#path/2) do
local j = #path - i + 1
path[i], path[j] = path[j], path[i]
end
return path
end
end
Sorry if its a bit lengthy, ive been working on this for awhile, and this module has been moreso for me to understand A* in a way. Is this usable for my game?