Hex Grid Code Refactoring and Maths Help

Discussion in 'Advanced Programming Discussion' started by tagwolf, Aug 4, 2019.

1. tagwolfMember

Joined:
Aug 6, 2016
Posts:
59
Hello, I am trying to refactor and cleanup my code to plug in a reusable and resizeable algorithm (including padding between hexcells). Unfortunately, I don't understand the maths well enough to get it done, but I have a static product that is working right now. hexcell is pretty much where I want it outside of the top-left x,y not mapping to where I want it. It'd also be nice to be able to easily flip the hex orientation. Any help would be much appreciated. Especially why my spacingh variable has to be -9....

The main part I need help with is the formula for spacing hexagons of any size/padding every other line and how that translates to gml. obj_hexgrid - create
So many hardcoded values Code:
gridw = 8;
gridh = 16;
spacingw = 64;
spacingh = -9;

for (i = 0; i < gridw; i ++)
{
for (j = 0; j < gridh; j ++)
{
if (j % 2 == 0)
{
instance_create_layer((x + spacingw) * i, (y + spacingh) * j, layer, obj_hexcell);
}
else
{
instance_create_layer((x + spacingw) * i + 96, (y + spacingh) * j, layer, obj_hexcell);
}
}
}

obj_hexcell - create
Code:
sides = 6;
sidelength = 64;
angle = 360/sides;

newangle = 0;
newx = x;
newy = y;

obj_hexcell - draw
Code:
draw_primitive_begin(pr_linestrip)
repeat(sides)
{
newangle += angle;
if newangle >= 360 {newangle = 0;}
oldx = newx;
oldy = newy;
newx = oldx - lengthdir_x(sidelength, newangle);
newy = oldy + lengthdir_y(sidelength, newangle);
draw_vertex(oldx,oldy);
}
draw_primitive_end();

Last edited: Aug 4, 2019