# Need a bit of help with some math in regards to hex nodes

After reading a fair amount on how to create hex grid based maps I decided to try my hand at creating a simple 2d map with just the hex tiles. I found that in order to facilitate the squiggly pattern needed for a hex map that the easiest (at least to me) is to add and subtract from one of the variables every time it generates a tile in whatever pattern needed(depending on if its a flat topped or pointy topped hex).

I’m using flat topped meaning that my Y axis is the same as in a square grid but my X axis has to squiggle in order to fit correctly this is what the below code is supposed to do:

``````void Start () {
for(y = 0; y < height; y = y + 0.88f){
for(x = 0; x < width; x = x + 0.769f ){

y = y + 0.451f; // this is supposed to work with the below y = y - 0.451f to increase, generate then revert to the y axis actual value

Vector3 spawnPoint = new Vector3(x, y, 0); //this code and the next two lines are what generate the hex's according to an array elsewhere
var groundNode = (GameObject)Instantiate (hexGridTiles [Random.Range (0, hexGridTiles.Length)], spawnPoint, Quaternion.identity);
groundNode.transform.SetParent(transform, true);

y = y - 0.451f;
}

}

}
``````

Instead the hex’s attempt to generate in a square grid fashion- heres a screenshot of whats happening:

The grids are stating with a Y pos of 0.451 and are not adding nor subtracting when moving on the X axis. They are also adding both Y values to the Y axis when it generates upwards meaning the first y grid after origin instead of being at 0.88 is sitting on 1.331.

Yet when I manually change the values to what they should be it looks like this

I’m either doing my math or my programming wrong but for the life of me I cant see where the mistake is. Any help/future tips on this, would be much appreciated.

It looks like you’re offsetting the y value for every column. Don’t you only want to do it for alternate columns?

I think something like this would do…

``````void Start ()
{
for (y = 0; y < height; y = y + 0.88f)
{
bool doOffset = false;
for(x = 0; x < width; x = x + 0.769f )
{
float offset = doOffset ? 0.451f : 0f;
y = y + offset;
Vector3 spawnPoint = new Vector3(x, y, 0);
var groundNode = (GameObject)Instantiate (hexGridTiles [Random.Range (0, hexGridTiles.Length)], spawnPoint, Quaternion.identity);
groundNode.transform.SetParent(transform, true);

y = y - offset;
doOffset = !doOffset;
}
}
}
``````