I have just posted a library of hex-grid utilities.
The library includes path-finding (using A-* a la Eric Lippert) and includes utilities for automated conversion between jagged (termed User) coordinates and non-jagged (termed Canonical) coordinates. The path-finding algorithm allows the step cost for each node to vary both with the entry hex and te traversed hex-side (though the example provided is simpler).
Also, elevated field-of-view using shadow-casting is provided, [edit: words removed].
Here is a code sample that converts readily between three hex-grid coordinate systems:
static readonly IntMatrix2D MatrixUserToCanon = new IntMatrix2D(2,1, 0,2, 0,0, 2);
IntVector2D VectorCanon {
get { return !isCanonNull ? vectorCanon : VectorUser * MatrixUserToCanon / 2; }
set { vectorCanon = value; isUserNull = isCustomNull = true; }
} IntVector2D vectorCanon;
bool isCanonNull;
static readonly IntMatrix2D MatrixCanonToUser = new IntMatrix2D(2,-1, 0,2, 0,1, 2);
IntVector2D VectorUser {
get { return !isUserNull ? vectorUser
: !isCanonNull ? VectorCanon * MatrixCanonToUser / 2
: VectorCustom * MatrixCustomToUser / 2; }
set { vectorUser = value; isCustomNull = isCanonNull = true; }
} IntVector2D vectorUser;
bool isUserNull;
static IntMatrix2D MatrixCustomToUser = new IntMatrix2D(2,0, 0,-2, 0,(2*Height)-1, 2);
static IntMatrix2D MatrixUserToCustom = new IntMatrix2D(2,0, 0,-2, 0,(2*Height)-1, 2);
IntVector2D VectorCustom {
get { return !isCustomNull ? vectorCustom : VectorUser * MatrixUserToCustom / 2; }
set { vectorCustom = value; isCanonNull = isUserNull = true; }
} IntVector2D vectorCustom;
bool isCustomNull;
IntMatrix2D
and IntVector2D
are homogeneous integer implementations of affine2D Graphics Vector and Matrix. The final divide by 2 on the vector applications is to re-normalize the vectors; this could be buried in the IntMatrix2D
implementation, but then the reason for the 7th argument to the IntMatrix2D
constructors is less obvious. Note the combined caching and lazy-evaluation of non-current formulations.
These matrices are for the case:
- Hex grain vertical;
- Origin in upper-left for Canonical & User coordinates, lower-left for Custom coordnates;
- Y-axis vertically down;
- Rectangular X-axis horizontally across; and
- Canonical X-axis to the North-East (ie up and to the right, at 120 degrees CCW from Y-axis).
The code library mentioned above provides a similarly elegant mechanism for hex-picking (i.e. identifying the hex selected with a mouse click).
In canonical coordinates, the 6 cardinal direction-vectors are (1,0), (0,1), (1,1) and their inverses for all hexagons, without the asymmetry of jagged coordinates.