- Home /
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.
This tutorial might help:
Answer by Bonfire-Boy · Oct 04, 2016 at 09:26 PM
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;
}
}
}
Yup this pretty much did it. Thank you I knew it was something simple I was missing.
Your answer
![](https://koobas.hobune.stream/wayback/20220612094012im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Interactive Hexagon Map Errors 0 Answers
Saving a Triple Byte Array [,,] 0 Answers
Creating an UI GPS map 0 Answers
Best practices for interactive hexagon map? 1 Answer
Assigning UV Map to model at runtime 0 Answers