What extra calculations i can remove/change to make it faster?
For now the timer(tick-s) is around 3 seconds, how could i reduce it?
-- A* Pathfinding in ROBLOX with Vector3 Nodes
local function Heuristic(a, b)
-- Use Manhattan distance as the heuristic
return (math.abs(a.X - b.X) + math.abs(a.Y - b.Y) + math.abs(a.Z - b.Z))
end
local function GetNeighbors(node)
-- Define your neighbors function here
-- For simplicity, let's assume the neighbors are directly adjacent on the grid
local neighbors = {}
local offsets = {
Vector3.new(1, 0, 0), Vector3.new(-1, 0, 0),
Vector3.new(0, 1, 0), Vector3.new(0, -1, 0),
Vector3.new(0, 0, 1), Vector3.new(0, 0, -1)
}
for _, offset in pairs(offsets) do
local inPart = #workspace:getPartBoundsInRadius(node + offset, 0.001) > 0
if inPart == false then
table.insert(neighbors, node + offset)
end
end
return neighbors
end
local function AStar(start, goal)
local openSet = {[start] = true}
local cameFrom = {}
local gScore = {[start] = 0}
local fScore = {[start] = Heuristic(start, goal)}
while next(openSet) do
-- Find the node in openSet with the lowest fScore
local current
for node in pairs(openSet) do
if not current or fScore[node] < fScore[current] then
current = node
end
end
if current == goal then
-- Reconstruct path
local totalPath = {current}
while cameFrom[current] do
current = cameFrom[current]
table.insert(totalPath, 1, current)
end
return totalPath
end
local offsets = {
Vector3.new(1, 0, 0), Vector3.new(-1, 0, 0),
Vector3.new(0, 1, 0), Vector3.new(0, -1, 0),
Vector3.new(0, 0, 1), Vector3.new(0, 0, -1)
}
openSet[current] = nil
for _, offset in pairs(offsets) do
local neighbor = current + offset
local inPart = #workspace:getPartBoundsInRadius(neighbor, 0.001) > 0
if inPart == false then
local tentative_gScore = gScore[current] + (neighbor - current).Magnitude
if not gScore[neighbor] or tentative_gScore < gScore[neighbor] then
-- This path to neighbor is better than any previous one
cameFrom[neighbor] = current
gScore[neighbor] = tentative_gScore
fScore[neighbor] = gScore[neighbor] + Heuristic(neighbor, goal)
openSet[neighbor] = true
end
end
end
end
-- Return an empty table if there is no path
return {}
end
wait(5)
local s = tick()
-- Define your start and goal points
local start = Vector3.new(1, 1, 1)
local goal = Vector3.new(40, 40, 40)
-- Run the A* algorithm
local path = AStar(start, goal)
-- Output the path
for _, node in ipairs(path) do
print(node)
end
s = tick()-s
print(s)```