Distance Function Produces Incorrect Results
Summary of error: If you plug in the hexagon that is Hex(q+1,r+1) as the 'other' parameter to the distance method you'll get a distance of 1 where you should be getting a distance of 2.
As it stands:
int distance(Hex other) {
int a = (q - other.q).abs();
int b = (r - other.r).abs();
int c = (a - b).abs();
return max(a, max(b, c));
}
Suggested:
int distance(Hex other) {
int a = (q - other.q).abs();
int b = (r - other.r).abs();
int c = (q + r - other.q - other.r).abs();
return (a + b + c) / 2;
}
Or as a single line:
int distance(Hex other) => ((q - other.q).abs() + (r - other.r).abs() + (q + r - other.q - other.r).abs())/2;
This is based on https://www.redblobgames.com/grids/hexagons/#distances
In the axial system, the third coordinate is implicit. Let's convert axial to cube to calculate distance:
function hex_distance(a, b): var ac = axial_to_cube(a) var bc = axial_to_cube(b) return cube_distance(ac, bc)
If your compiler inlines axial_to_cube and cube_distance, it will generate this code:
function hex_distance(a, b): return (abs(a.q - b.q) + abs(a.q + a.r - b.q - b.r) + abs(a.r - b.r)) / 2