Skip to content

Instantly share code, notes, and snippets.

@dshook
Last active June 16, 2019 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dshook/56ebc66f424e2bf852e2c8d1c26ed12f to your computer and use it in GitHub Desktop.
Save dshook/56ebc66f424e2bf852e2c8d1c26ed12f to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class HexPerimeter
{
public static List<HexCell> FindPerimeterLoop(List<HexCell> cells){
//start by finding the top right most cell to start a loop from
var startCell = cells.OrderByDescending(t => t.coordinates.Z).ThenByDescending(t => t.coordinates.X).FirstOrDefault();
//trace right and down as much as we can until the bottom is found, then start going left and up
//It's possible to go back the way we came if there is a one cell peninsula
var perim = new List<HexCell>();
var travelDirection = HexDirection.SE;
var currentCell = startCell;
do
{
var directionPriorities = directionPriority(travelDirection);
foreach (var direction in directionPriorities)
{
var nextCell = currentCell.GetNeighbor(direction);
//Add if in the original set of cells
if (cells.Any(c => nextCell == c))
{
perim.Add(currentCell);
travelDirection = direction;
currentCell = nextCell;
break;
}
}
}
while (currentCell != startCell);
return perim;
}
//Which way should we go given which way we came from?
//The way the directions are set up this works out to going around clockwise given the start at top
static IEnumerable<HexDirection> directionPriority(HexDirection dir){
yield return dir.Previous();
yield return dir;
yield return dir.Next();
yield return dir.Next2();
yield return dir.Opposite(); //Last resort go back the way we came
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment