How to put map into table with closest neighbors more efficiently

Hi, I’m making a voxel game. I need to get a part and be able to see its closest neighbors. My solution was to put it into a dictionary. Is there a more efficient way to go about this or make it more optimized? Currently, it takes around 100ms for 60k parts.
Code:

local directions = {
	["Left"] = Vector3.new(0,GRID_SIZE,0),
	["Right"] = Vector3.new(0,-GRID_SIZE,0),
	["Forward"] = Vector3.new(0,0,GRID_SIZE),
	["Backward"] = Vector3.new(0,0,-GRID_SIZE),
	["Up"] = Vector3.new(0,GRID_SIZE,0),
	["Down"] = Vector3.new(0,-GRID_SIZE,0)
}

for i,v in pairs(game.Workspace.Map:GetChildren()) do
	neighbors[v.Position] = {
		["self"] = v,
	}
	for direction, vector in pairs(directions) do
		neighbors[v.Position][direction] = neighbors[v.Position + vector] and v.Position + vector or false
		if neighbors[v.Position][direction] then
			local updateLeaf = neighbors[neighbors[v.Position][direction]]
			for j,k in pairs(directions) do
				if k == -vector then
					neighbors[neighbors[v.Position][direction]][k] = v.Position 
				end
			end
		end
	end
end
1 Like

Well the major issue is you are searching through literally every part in the game.

If I was to make a voxel game, the first thing I would try to do is represent every part in a 3D array. That way to reference a parts neighbors you can just do something like this:

-- x, y, z can be calculated from the position of a part.  The specifics would depend on implementation though, so I've left declaration out.
local part = map[x][y][z]
local neighbors = {
    map[x-1][y][z],
    map[x+1][y][z],
    map[x][y-1][z],
    map[x][y+1][z],
    map[x][y][z-1],
    map[x][y][z+1]
}

That way instead of having to search through literally every part, you can just directly reference it. Makes accessing them way faster at cost of slight memory increase.

3 Likes

Thanks, I’m stupid and seem to have forgotten about region3 and the new spatial query API. Thanks for the answer though :smile: