Page 1 of 1

getting neighbors of a hexagon in a hexagon grid?

Posted: Tue Oct 03, 2017 10:51 am
by Ze Ducktor
I'm trying to make a game in Love2D that uses a hexagon grid. The problem is, the library I'm using has all the functions I need, except a function that allows me to get the surrounding neighbors of a hexagon. The function IS there, it's just empty (the github page for it hasn't been edited in 3+ years so there's little chance of it ever being updated).

If anyone could look at the source code for the library and tell me how to go about implementing the missing function, that'll be great.

Here's the source code for the library.

Re: getting neighbors of a hexagon in a hexagon grid?

Posted: Tue Oct 03, 2017 11:42 am
by grump
There's a certain risk involved in using version 0.0.1 of incomplete, unmaintained and undocumented libraries no one else has ever used. This will probably not be the last problem you encounter.

I don't have a quick answer for you, but I can recommend this tutorial. I explains how to find neighbors, and the coord conversions you may need to make it work with this library.

It also provides an implementation guide with code that is probably of better quality than what you're currently using.

Hope that helps.

Re: getting neighbors of a hexagon in a hexagon grid?

Posted: Tue Oct 03, 2017 2:19 pm
by josip
The code lib you have was actually derived from tutorial that grump referenced. I have also used same reference material to implement my hex grid, but I wrote just the stuff I needed.

To answer your question, I implemented neighbors by manually creating the table with (q, r) coordinates of all six neighbor tiles from tile located at 0,0.

Code: Select all

local axial_directions = {
   { 1, -1}, { 0, -1}, {-1,  0}, {-1,  1}, { 0,  1}, { 1,  0}
}
If you want neighbors of (q,r), you go through the table and calculate coordinated by adding your coordinates with coordinates from table.

I also implemented lua-style iterator that you can use with for loop, so you can visit all tiles in some radius around central tile in spiraling order.

You can check out my implementation here: https://pastebin.com/0WmyB2hL

It would be nice to turn this into actual repo so people can build on it, but I don't have time to mantain it :(