Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

31 Commits

Repository files navigation

Hexgrid

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.privatestaticfinalfloatHEX_GRID_SIZE = 30f;
//Keep these as they areprivatestaticfinalfloatHEX_GRID_FACTOR_X = HEX_GRID_SIZE / 2f;
privatestaticfinalfloatHEX_GRID_FACTOR_Y = (float) (HEX_GRID_SIZE / 2f * Math.tan(Math.toRadians(60)));
privatestaticint[] getHexGrid(intpx, intpy) {
intsgx = (int) (px / HEX_GRID_FACTOR_X);
intsgy = (int) (py / HEX_GRID_FACTOR_Y);
intbgx = sgx / 3;
intbgy = sgy / 2;
if (sgx % 3 == 2) {//If you are in the right third of the big gridfloatipx = px / HEX_GRID_FACTOR_X - sgx;//Internal positions inside the small grid cells in percentfloatipy = 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 rightbgx += 1;
}
}
if ((bgx & 1) == 0) {//if you are in an//even column: return the coordinates as isreturnnewint[] {bgx, bgy};
} else {
//uneven column: add one to the big grid y coordinate// if you are in the lower part of the big grid cellreturnnewint[] {bgx, bgy + ((sgy & 1) == 0? 0 : 1)};
}
}

Hexgrid with small and big grid visible:
alt text


Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

About

Hexgrid generator

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages