Reputation: 157
I'm using C# in Unity to make a game with a hexagonal grid. I'm trying to make the map in the shape of a hexagon rather than a rectangle. However, in order to do this with a grid, I need to apply 6 conditions (one for each side) to the rectangular grid to filter out the tiles which don't fall within the space we've determined to be within the hexagon. For instance, using pseudo-code:
foreach(tile in rectangle) { if((y <= 2/3*x + 0.5) && (condition2) && ...) { Debug.Log("It's a tile in the hexagon!") } }
I'm not great at trig, so I've been stumped on how to approach this for a while. In fact, I can't get a single condition down that would define a side of a hexagon (other than the top and the bottom stretches, which are done by default). Any help would be appreciated. Thanks!
(Additional information: the left and right sides are X and are 0.866 apart; top and bottom points are Z and are 1 apart but are fitted such that every other tile in a row is 0.25 closer to its adjacent row.)
Upvotes: 0
Views: 515
Reputation: 157
I figured it out! I made a perfect hexagon in desmos: https://www.desmos.com/calculator/8tqplz09tt
Then, I converted this to code:
float standardUnitZ = ((mapSize.z * chunkSize.z) - 1f);
float normalUnitZ = standardUnitZ * (13f/15f);
float thisX = ((cz * mapSize.z) + hz);
float sqrt3 = (float)Math.Sqrt(3f);
if (
(theseFinalCoords.z >= (((1 - (13f / 15f)) * normalUnitZ) / 2))//1 BOTTOM
&& (theseFinalCoords.z <= normalUnitZ - (((1 - (13f/15f)) * normalUnitZ) / 2))//2 TOP
&& (theseFinalCoords.z <= sqrt3*thisX + (normalUnitZ / 2f))//3 TOP LEFT
&& (theseFinalCoords.z >= -sqrt3*thisX + (normalUnitZ / 2f))//4 BOTTOM LEFT
&& (theseFinalCoords.z <= -sqrt3*thisX + 2.2320508075f*normalUnitZ)//5 TOP RIGHT
&& (theseFinalCoords.z >= sqrt3*thisX - 1.2320508075*normalUnitZ)//6 BOTTOM RIGHT
)
A little more work to do possibly, but here's the final result:
Upvotes: 1