Get surrounding chunk data based on existing position


I’m working on a system that loads data unique to each chunk. The issue I’m having is I don’t know how to get the data from the surrounding chunks.

For example, if a player is in Chunk 0,0 I want to get data from all the chunks surrounding it. (All the chunks in the image)

The tables holding the chunk data look like this:

local ChunkData = {
[00] = 'chunkdatahere',
[01] = 'chunkdatahere',
[11] = 'chunkdatahere',
[10] = 'chunkdatahere',

They’re formatted by XZ. So [00] is 0,0 and [01] is 0,1. I’ll need to call tostring after doing math to be able to access negative chunk coordinates. But that isn’t important right now.

Anyways, I just need help writing or atleast some guidance on how to start writing something like this. I’m thinking there’s an easy math solution, but I don’t know where to start as I’ve never done something like this before.

Any help is appreciated!

just here to say you should probably store that key as a vector2.

If you are just trying to attempt loading in parts of your map based on the player’s position, use streamingenabled.

You could get the player XZ and check as Table[PlayerX-1,PlayerZ-1] and do the same for all +/- variants

1 Like

This is known as neighbors, just add and minus the xy coordinates to get the next chunk like @DenisxdX3 said. Here was my implementation, your definitions of up,right,left,down might vary depending on how you view the Axis:

function Grid:GetNeighboringCells(x, y)
	local neighborCoordinates = {
		["Up"] = {x, y-1};
		["Right"] = {x+1, y};
		["Down"] = {x, y+1};
		["Left"] = {x-1, y};
	--top/bottom = y coordinates, right/left = x coordinates
	local diagonalCoordinates = {
		["Up Right"] = {x+1, y-1};
		["Up Left"] = {x-1, y-1};
		["Down Right"] = {x+1, y+1};
		["Down Left"] = {x-1, y+1};

Then you loop through each value coordinate and get the chunk data.

Bonus info:
Redblob games website, also includes more advanced grids like hexagonal and triangles.


This is amazing, thank you!

I’ll be adding this to my script. :slight_smile:

1 Like