Get neighbors on hex grid

Hello! I recently made a simple hex grid. However, I want each Tile to be able to know which tiles are adjacent to it.

The code is:

local function AddTile(xPos : number, zPos: number)
	xPos *= tileWidth

	if zPos % 2 == 0 then
		xPos += tileWidth * 0.5
	end
	zPos *= tileHeight * 0.75

	local tile = tile:Clone()
	tile.CFrame = CFrame.new(Vector3.new(xPos, 0, zPos)) * CFrame.fromEulerAngles(0, math.rad(30), 0)
	tile.Parent = workspace.Terrain.Tiles
end

GenerateMap.Generate = function(mapWidth : number, mapHeight : number)
	gridWidth = mapWidth
	gridHeight = mapHeight
	
	for zPos = 1, gridWidth do
		for xPos = 1, gridHeight do
			AddTile(xPos,zPos)
		end
	end
end
1 Like

This site has 25 years worth of hex grid resources and a whole section about neighbors which should help you:

You can probably find some code that you can copy from stackOverFlow or something like that as well if you don’t want to bother with figuring this out.

1 Like

There is a maze technique called Who’s Your Neighbor. That may help with this thinking also.

This has helped a lot, but I’m a little confused on something. Maybe you can help me out.

I have my array here:

local direction_differences = {
	{1, 0}, {1, -1}, {0, -1}, {-1, 0}, {0, 1}, {1, 1}
}

corresponding to this:

However in their code they have “direction”, I’m not quite sure what I should put there.

local parity = bit32.band(zPos)
local diff = direction_differences[parity][]

Trying to convert this all to Roblox has been a little confusing haha, but very useful resource!

Edit: I’m also not sure if I did the array exactly right.

1 Like

The direction is a number from 1-6. 1 would be east and it would go counterclockwise (2 would be north-east, 3 would be north-west etc)

You can hover over the directions and the correct table will get highlighted in the website, that might help you get that “click” in your brain.


(not sure if this picture is useful at all, but I believe it’s easier to understand something if it’s visually brought out)

1 Like

Thank you, that helps a lot actually.
I gotta run to the dentist, but I’ll do this when I get back!
Thanks again for all the help.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.