You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
localAStar=require'astar'localmap= {}
localcached_nodes= {}
-- Node must be able to check if they are the same-- Cannot directly return different tables for the same coord-- The library doesn't change nodes, so you able to reuse your node or create a C struct for fasterlocalfunctionget_node(x, y)
localrow=cached_nodes[y]
ifnotrowthenrow= {}; cached_nodes[y] =rowendlocalnode=row[x]
ifnotnodethennode= { x=x, y=y }; row[x] =nodeendreturnnodeendlocalneighbors_offset= {
{ -1, -1 }, { 0, -1 }, { 1, -1 },
{ -1, 0 }, { 1, 0 },
{ -1, 1 }, { 0, 1 }, { 1, 1 },
}
-- Return all neighbor nodes. Means a target that can be moved from the current node-- add_neighbor_cb: function(new_node, cost)-- cost is optional, call map:get_cost to get cost if no cost valuefunctionmap:get_neighbors(node, from_node, add_neighbor_cb, userdata)
fori, offsetinipairs(neighbors_offset) doadd_neighbor_cb(get_node(node.x+offset[1], node.y+offset[2]))
endend-- Cost of two adjacent nodes.-- Distance, distance + cost or other comparison value you wantfunctionmap:get_cost(from_node, to_node, userdata)
returnmath.sqrt(math.pow(from_node.x-to_node.x, 2) +math.pow(from_node.y-to_node.y, 2))
end-- For heuristic. Estimate cost of current node to goal node-- As close to the real cost as possiblefunctionmap:estimate_cost(node, goal_node, userdata)
returnself:get_cost(node, goal_node)
endlocalfinder=AStar.new(map)
localstart, goal=get_node(1, 1), get_node(3, 4)
localuserdata= { 'mydata' }
localpath=finder:find(start, goal, userdata)
ifpaththenfor_, nodeinipairs(path) doprint(node.x, node.y)
endelseprint("Not found path")
end
And you can try to run the main.lua by Love2d
Better path
This article tells us how to generate a smooth path with a turning radius.