Skip to content

Instantly share code, notes, and snippets.

@vncastanheira
Last active January 10, 2024 02:26
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 vncastanheira/f69d9a6b1db025025708eae8b3cec90d to your computer and use it in GitHub Desktop.
Save vncastanheira/f69d9a6b1db025025708eae8b3cec90d to your computer and use it in GitHub Desktop.
HexUtils
using UnityEngine;
// Helper script to find out adjancent cells in a hexagonal grid
public static class HexGridUtils
{
public readonly static Vector2Int[] EvenRowsTable = new Vector2Int[]
{
new Vector2Int(1, 0),
new Vector2Int(0, -1),
new Vector2Int(-1, -1),
new Vector2Int(-1, 0),
new Vector2Int(-1, 1),
new Vector2Int(0, 1),
};
public readonly static Vector2Int[] OddRowsTable = new Vector2Int[]
{
new Vector2Int(1, 0),
new Vector2Int(1, -1),
new Vector2Int(0, -1),
new Vector2Int(-1, 0),
new Vector2Int(0, 1),
new Vector2Int(1, 1),
};
public static Vector2Int[] GetOffsetTable(Vector2Int cell) => cell.y % 2 == 0 ? EvenRowsTable : OddRowsTable;
public static bool IsAdjacentCell(Vector2Int primaryCell, Vector2Int otherCell)
{
Vector2Int[] table = GetOffsetTable(primaryCell);
for (int i = 0; i < table.Length; i++)
{
if (primaryCell + table[i] == otherCell)
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment