Today we're going to learn how to create a nice border around the perimeter of an area in a hex map using Unity and a LineRenderer. Here I have it as a dotted purple line but you can make it look like anything you want with the flexibility of the line renderer!
The foundation of the hex code here is adapted from the Hex Map Series by Catlike Coding which has been super helpful for getting started. So if there's any bits of code I missed here it's likely from there, but please let me know in the comments if you're getting stuck or confused anywhere.
First up we'll need a little background code for the data we'll be operating on for the rest of this article.
1. Find the Area
The first step is finding the set of cells that we'll use to find the perimeter around. For my implementation I started with a variation on a flood fill algorithm that is also close to a Voronoi diagram. There's a great article here about it as well as many more great articles about hex maps, pathfinding and much more.
Since my city areas are changing infrequently I update them at startup and whenever one of the cities grows in influence (which affects their max radius of influence).
2. Find the perimeter of the area
Now that we have a set of cells for an area we need to find the cells on the perimeter of the area so that we can then find the points along edges of the cells for the line to go.
This works by finding the top right-most cell and then marches around the perimeter by prioritizing the direction to travel in. For example, if our last move was to the cell south east of us our priorities would look like this:
This priority ordering will ensure we stay along the outside edge of the area.
We also need to include the 5th priority as going back to where we came from in the case where there is a peninsula of cells that stick out from the rest. In that case our perimeter will contain those cells twice as the algorithm marches out and back, but this is what we want so that the line can follow around the outside.
3. Find the points for the line
And now for the fun part: finding all the world coordinates for our line renderer. We'll do this by iterating over the perimeter cells keeping track of which direction we came from and which direction we're going. These directions will let us determine which kind of "bend" we're dealing with. This bend type will then determine how many corners of the current hex cell we'll need to add to our line before moving on.
And that's the gist of it! All that's left is the function to tie it all together:
When you set up your LineRenderer just make sure the
Use World Space and
Loop boxes are checked.
Hope you learned something and saved some time!Back to home More blog posts