Hey guys, been a while since I’ve used the dev forum.
I’m working on creating flow fields that will be used to pathfind for large groups of units to essentially work towards the same goal.
For an explanation of flow fields in context see:
Flow-Field Explanation
This is the code I use to represent my world as a 2d grid. Each X position is an array that is indexed by corresponding Y positions. (eg. array[x][y]). At a[x][y] exists a “cell,” which is essentially a table of information for that location in the grid.
-- the meat of the code
function Grid.new(gridSize)
local grid = {}
-- create new Cell {} at every grid [x][y] index
for x = 1, gridSize.X do
grid[x] = {}
for y = 1, gridSize.Y do
grid[x][y] = {}
end
end
return grid
end
My issue is that this method of generation is very slow when creating large grids.
For example, through some (probably slightly inaccurate) tick() measurements, a 1000x1000 grid takes about 3 to 4.5 seconds to generate. In fact, running this through some custom debug code I’ve made to visualize it usually ends in some sort of “execution run time exceeded” error (or something of that nature) when trying to visualize large grids.
Here’s an example of what this may look like when implemented and later visualized:
The green cell is the goal cell and the surrounding cells all point to it. Essentially an AI would know which cell it’s standing in and follow the direction stored at that location. Thus finding its way to the goal.
(I’ve excluded how this is all drawn and calculated as it’s not important.)
This is a solution I tried with representing the grid but the results were more or less the same:
-- from lua.org/pil/
mt = {}
for i=1,N do
for j=1,M do
mt[i*M + j] = 0
end
end
Thus the time taken seems to be mostly due to the sheer amount of code being run than anything with indexing/writing to a table or memory itself (or so I believe).
One thing I’ve yet to do but am considering is splitting the world up into larger tiles, then figuring out which path the units must take through the large tiles to reach a certain goal. Once that path of large tiles is found, I would then proceed to generate smaller tiles inside of those for avoiding collisions and whatnot. This method can be seen here: Pathfinding w/ 30k Units
Overall, I hope one of you can help me figure out a method that speeds up generation time. Ideally, I’d like to be able to still get the information about my tiles in terms of X,Y notation, whether that be literal array[x][y]
as I’m doing now or something less intuitive.
Thanks for reading this far, and let me know about any questions/corrections I should address.