Function that returns close chunks?

I’m trying to make a function that would return my chunks around the player with an option on range which basically means it will check chunks chunk/s away from player.
My code looks like this:

local function getCloseChunks(range)
	local onChunk = getOnChunk().Position
	local closeChunks = {}
	local distance = chunkSize.X
	
	for i = 1, range do
		-- get center --
		table.insert(closeChunks, getOnChunk())
		
		-- get right, left, front, back --
		table.insert(closeChunks, getChunk(Vector3.new(onChunk.X +distance, onChunk.Y, onChunk.Z)))
		table.insert(closeChunks, getChunk(Vector3.new(onChunk.X -distance, onChunk.Y, onChunk.Z)))
		table.insert(closeChunks, getChunk(Vector3.new(onChunk.X, onChunk.Y, onChunk.Z +distance)))
		table.insert(closeChunks, getChunk(Vector3.new(onChunk.X, onChunk.Y, onChunk.Z -distance)))
		
		-- get corners --
		table.insert(closeChunks, getChunk(Vector3.new(onChunk.X +distance, onChunk.Y, onChunk.Z +distance)))
		table.insert(closeChunks, getChunk(Vector3.new(onChunk.X +distance, onChunk.Y, onChunk.Z -distance)))
		table.insert(closeChunks, getChunk(Vector3.new(onChunk.X -distance, onChunk.Y, onChunk.Z +distance)))
		table.insert(closeChunks, getChunk(Vector3.new(onChunk.X -distance, onChunk.Y, onChunk.Z -distance)))
		
		distance += chunkSize.X
	end
	
	return closeChunks
end

But it has a problem, if the range is higher than 1 then this happens:
image
Black text just shows how the code works, but red crosses show which chunks get added as close chunks if the range is higher than 1. And chunks without the cross (and black text) are ones which don’t get added.

Does anyone know a better way of doing it or a fix for it?

1 Like
function getPointsInRange(center, range)
    local points = {}
    for x = -range, range do
    for z = -range, range do
        table.insert(points, center + Vector3.new(x, 0, z)
    end 
    end
    return points
end

local function getChunksInRange(center, range)
    local chunks = {}
    for _, pointInRange in ipairs(getPointsInRange(center, range)) do
        table.insert(chunks, getChunk(pointInRange))
    end
    return chunks
end

local closeChunks = getChunksInRange(getOnChunk().Position, range)
1 Like

Thank you so much it works perfectly!

1 Like