- Home /
Hexagonal grid
Hi, i have problem with my grid bcs it looks like that and i want to make it more "normal". It means i want rectangular hexagonal grid and i cant find where i make mistake
There is my code
public class HexMap : MonoBehaviour
{
public int numColumn = 40;
public int numRow = 20;
public GameObject hexPrefab;
float radius = 1f;
Vector3 position;
void Start()
{
GenerateGrid(numRow, numColumn);
}
public void GenerateGrid(int numRow, int numColumn)
{
float width = WidthHex();
float horiz = width;
float vert = HeightHex(radius) * 0.75f;
for (int column = 0; column < this.numColumn; column++)
{
for (int row = 0; row < this.numRow; row++)
{
position = new Vector3(
horiz * (column + row * 0.5f),
0,
vert * (row)
);
if (row % 2 == 0)
{
position.x = horiz * (column + row * 0.5f - row * 0.5f);
}
Instantiate(
hexPrefab,
position,
Quaternion.identity,
this.transform
);
}
}
}
public float HeightHex(float radius)
{
return radius * 2;
}
public float WidthHex()
{
return SpacingWidth() * HeightHex(radius);
}
public float SpacingWidth()
{
return Mathf.Sqrt(3) * 0.5f;
}
public float Horiz()
{
return WidthHex();
}
}
Can anyone tell me where is problem? Thank you!
Answer by Bunny83 · Feb 05, 2019 at 03:41 AM
Well your main issue is this line:
horiz * (column + row * 0.5f),
This will make your cell go more to the right the higher the column or the row index is. So you essentially shift diagonally and that's what you see in your image.
The next issue is this part which looks like an attempted fix:
if (row % 2 == 0)
{
position.x = horiz * (column + row * 0.5f - row * 0.5f);
}
Note that + row * 0.5f - row * 0.5f
will cancel each other so the line reads just:
position.x = horiz * (column);
This is why every second row does represent a rectangle since here the x position only depends on the column index.
What you actually want to do is have the x offset alternate between the rows. Something like this:
position = new Vector3(
horiz * (column + (row%2) * 0.5f),
0,
vert * (row)
);
Note that "(row%2)" will alternate between 0 and 1 for each row. So every second row gets a 0.5 offset on the x.
Oh, its working perfectly now, Thank u man for explained me :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612191118im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Tiles Slow Down Game 0 Answers
Hexagonal Grid mesh issues 0 Answers
How to "blend" two+ textures at runtime? 0 Answers