These two classes are the essential building blocks for building all sorts of hex-based grids, including but not limited to puzzles, tower defense, strategy and tactics games.
Important! Even though just copy/pasting the code will give you what you want, you won't be able to go much further unless you understand the bare essentials. I strongly recommend taking a cup of tea/coffee and reading the first half of https://www.redblobgames.com/grids/hexagons/ which explains pretty much everything you need to know about hex grids.
Copy and paste into your project. Hex
is "model", i.e. it is a plain struct
which doesn't derive from MonoBehaviour
. Its purpose is to encapsulate a pair of integer coordinates in hex grid space (in skewed coordinate system) and to perform conversions to/from world space, alongside some basic traversal methods.
The Node
class inherits from MonoBehaviour
and therefore can be attached to any game object. When you do so, said object automagically begins to snap to a logical hexagonal floor, when you move it in your editor. Please note that by "floor" we mean world XZ plane by default; changing that is trivial by tweaking WorldToPlanar
and PlanarToWorld
static methods.
The dimensions of grid cell are chosen in a way that Unity's unit sphere (with radius 0.5f
) in inscibed into a unit hexagon of grid. Which means, the inradius of hexagonal grid is 0.5f
. It is relatively easy to modify this: you only need to modify 4 basis vectors (Q_BASIS, R_BASIS, Q_INV, R_INV) which are responsible for converting the coordinates.
Node
also exposes a way to snap rotations to hexagonal dimensions, by using integer multiples of 60 degrees. By convention adopted from RedBlobGames the dir
integer is constrained to [0, 5]
range and is a universal way to address neighbours and all direction-related problems such as line of sight, traversal, pathfinding, etc. Our Hex Laser Puzzle game makes extensive use of that :)