Add utils for hexagonal grild #50

Merged
tipragot merged 23 commits from hex-utils into main 2024-02-14 17:49:08 +00:00
Showing only changes of commit fafdcc0b0b - Show all commits

View file

@ -16,10 +16,10 @@ impl<T: Signed + PartialEq + Copy + PartialOrd> HexNumber for T {}
/// [documentation](https://www.redblobgames.com/grids/hexagons/#coordinates).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct HexPosition<T: HexNumber> {
/// Q coordinate
/// Q coordinate.
pub q: T,
/// R coordinate
/// R coordinate.
pub r: T,
}
@ -46,13 +46,9 @@ impl<T: HexNumber> HexPosition<T> {
/// assert_eq!(a.distance_to(&b), 2);
/// ```
pub fn distance_to(&self, other: &Self) -> T {
// dx = |x1 - x2| where x = q
// Calculate the difference between the q and r coordinates.
let dq = self.q - other.q;
// dy = |y1 - y2| where y = r
let dr = self.r - other.r;
// dz = |z1 - z2| where z = -q - r
let dz = self.q + self.r - other.q - other.r;
// Manhattan distance = (abs(dq) + abs(dr) + abs(ds)) / 2