How would i make my pathfinding to be faster?
local function heuristic(PosA, PosB)
return (PosA - PosB).magnitude
end
local function snap(pos : Vector3)
return Vector3.new(math.floor(pos.X/3)*3+1.5,math.floor(pos.Y/3)*3+1.5, math.floor(pos.Z/3)*3+1.5)
end
local blocks = {}
for i,v in pairs(workspace.WalkableParts:GetChildren()) do
local rounder = snap(v.Position)
blocks[rounder] = 1
end
local function getNeighbors(node, walkableParts)
local neighbors = {}
local directions = {
Vector3.new(3, 0, 0), Vector3.new(-3, 0, 0),
Vector3.new(0, 0, 3), Vector3.new(0, 0, -3),
Vector3.new(3, 0, 3), Vector3.new(3, 0, -3),
Vector3.new(-3, 0, 3), Vector3.new(-3, 0, -3)
}
for _, direction in ipairs(directions) do
local neighborPos = snap(node + direction)
if blocks[neighborPos] == nil then
table.insert(neighbors, neighborPos)
end
end
return neighbors
end
local function reconstructPath(cameFrom, current)
local totalPath = {current}
while cameFrom[current] do
current = cameFrom[current]
table.insert(totalPath, 1, current)
end
return totalPath
end
local function aStar(start, goal, walkableParts)
local openSet = {start}
local cameFrom = {}
local gScore = {[start] = 0}
local fScore = {[start] = heuristic(start, goal)}
local s
while #openSet > 0 do
table.sort(openSet, function(a, b) return fScore[a] < fScore[b] end)
local current = table.remove(openSet, 1)
if (current - goal).Magnitude < 1 then
s = reconstructPath(cameFrom, current)
return reconstructPath(cameFrom, current)
end
for _, neighbor in ipairs(getNeighbors(current, walkableParts)) do
local tentativeGScore = gScore[current] + (current - neighbor).magnitude
if tentativeGScore < (gScore[neighbor] or math.huge) then
cameFrom[neighbor] = current
gScore[neighbor] = tentativeGScore
fScore[neighbor] = gScore[neighbor] + heuristic(neighbor, goal)
if not table.find(openSet, neighbor) then
table.insert(openSet, neighbor)
end
end
end
end
end
-- Example usage
local function moveToPosition(path)
for _, part in ipairs(path) do
print(part.Position)
part.Color = Color3.new(1, 0, 0.0156863)
end
end
local startPart = workspace.Start.Position
local goalPart = workspace.Target.Position
while wait(1) do
if startPart and goalPart then
local path = aStar(startPart, goalPart, blocks)
if path and path[2] then
print(path[2])
startPart = path[2]
local a = Instance.new("Part", workspace)
a.Anchored = true
a.Size = Vector3.new(3,3,3)
a.CanCollide = false
a.Color = Color3.new(0, 0, 0.498039)
a.Position = path[2]
else
warn("No path found!")
end
else
warn("Start or goal part not found in walkable parts!")
end
end
It runs very slow, Can anyone help me to optimize it?