Tile HEx Generator


After playing a game called For The King I noticed the tiles it was using to generate was hexagons. So I decided to create a small scale hex tile generator for fun..

The math


In the OnSceneGUI I first start off drawing the circle in which I will base my points needed to generate for the hex. As seen on the right I use a for loop to create the 6 points for the hex using an function I created called DirFromAngle(). What this function does is get a direction passing an angle into and using SOHCAHTOA. I then create a point from each angle of an hex which is in increment of 60 degrees starting from 30. This create all six points need for the hex. Afterwards I draw all the points to confirm if it in the correct location.

Afterwards I draw all the lines of the hex to have a better representation of the shape as a whole. I then create the midpoints of each side of the hex. I know each point of the hex so I do a simple lerp calculation to get the midpoint of each point to the next point. Again I draw the midpoints to confirm to be in correct location.

After creating the hex with all it sides and points/midpoints I can finally find the points or location of the other hexes to generator in the future. In order to generate these points I get the distance of the center of the object and midpoint of one side. I then get a normilze direction of the midpoint pointing outwards toward the edge of the side. I then use the midpoint vector3 add the direction multiply with the distance to get the other hex spawn point when I need to generate the other hexes. Like always I then draw where those points are to confirm visually if they are in the correct postion.

THE generation


Now for the generator I then translate all I've learn and instead of doing the math for the hexes I translate them into functions such as GetMidpoints() and GetPoints(). I such as this one GenerateTiles(). What this does is loop through all the spawnpoints for the tiles next to the tiles and does an Physics.OverlapSphere(). Using the collider array it returns I check if their already an tile in place of the spawnpoint to not generate otherwise instantiate an hex/tile. I then for some varielty in the tile material I change the terrain type and use a 50% chance for a different terrain type than its own.

Results