Hexgrid generator
Generates a hexgrid by dividing each pixel into an 10x17 small grid and an 3x2 big grid (of the smaller grid) and returns the coordinate to the corresponding hex cell.
Note: only use positive coordinates or the algorithm will mess up! I have to fix that bug someday...
Also Note: the hex grid labeled (0|0) in the Test.png is actual hex grid (1|2)! The (0|0) grid lies in the upper-left most position. The way the numbers are rendered now is just easier to read.
Algorithm:
//This is the side length of the hexagon. You can freely change this.
private static final float HEX_GRID_SIZE = 30f;
//Keep these as they are
private static final float HEX_GRID_FACTOR_X = HEX_GRID_SIZE / 2f;
private static final float HEX_GRID_FACTOR_Y = (float) (HEX_GRID_SIZE / 2f * Math.tan(Math.toRadians(60)));
private static int[] getHexGrid(int px, int py) {
int sgx = (int) (px / HEX_GRID_FACTOR_X);
int sgy = (int) (py / HEX_GRID_FACTOR_Y);
int bgx = sgx / 3;
int bgy = sgy / 2;
if (sgx % 3 == 2) {//If you are in the right third of the big grid
float ipx = px / HEX_GRID_FACTOR_X - sgx;//Internal positions inside the small grid cells in percent
float ipy = py / HEX_GRID_FACTOR_Y - sgy;
// (bgx & 1) == (sgy & 1) is a "chess - pattern" check
// if true you have an edge from the upper-left to lower-right corner
// otherwise you have an edge from the lower-left to upper-right corner.
// Then it checks if you are part of the cell belonging to the left hex grid cell or the right
// hex grid cell and updates the big grid coordinate accordingly.
if (ipx > ((bgx & 1) == (sgy & 1)? ipy : (1 - ipy))) {
//belongs to the hex grid cell to the right
bgx += 1;
}
}
if ((bgx & 1) == 0) {//if you are in an
//even column: return the coordinates as is
return new int[] {bgx, bgy};
} else {
//uneven column: add one to the big grid y coordinate
// if you are in the lower part of the big grid cell
return new int[] {bgx, bgy + ((sgy & 1) == 0? 0 : 1)};
}
}
Hexgrid with small and big grid visible:
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.