• Welcome to the new COTI server. We've moved the Citizens to a new server. Please let us know in the COTI Website issue forum if you find any problems.

Hex distance

whartung

SOC-14 1K
Well, I just found out that my hex distance maths don't work :(.

CLOSE! but...

There are all sorts of solutions on the internet (which I surveyed when I wrote mine a zillion years ago), but none are drag and drop specifically with the way are hexes are numbered, etc. And I can't explain what mine is doing (right or wrong) anyway.

So, curious what others are using.

Here's what I have.

Code:
    public int hexDistance(int x1, int y1, int x2, int y2) {

        int ax = x1 - floor2(y1);
        int ay = x1 + ceil2(y1);
        int bx = x2 - floor2(y2);
        int by = x2 + ceil2(y2);
        int dx = bx - ax;
        int dy = by - ay;
        if (Math.signum(dx) == Math.signum(dy)) {
            return Math.max(Math.abs(dx), Math.abs(dy));
        }
        return Math.abs(dx) + Math.abs(dy);
    }

    private int floor2(int x) {
        return ((x >= 0) ? (x / 2) : (x - 1) / 2);
    }

    private int ceil2(int x) {
        return ((x >= 0) ? ((x + 1) / 2) : x / 2);
    }

It fails for 1903 to 1805. I get 2 instead of 3. (Subsector format which is column and row order, so its column 19 and row 3).

Code:
hexDistance(19, 3, 18, 5)

Math.signum returns 0 for zeros, -1 for negative numbers and +1 for positive numbers (BASIC SGN function).

So, just curious what others are using for this.
 
old c# code where W1, W2 were the hex worlds 0101, 0202 sort of thing

Code:
 public int calcDistance(string W1, string W2)
        {
            int ST1 = Convert.ToInt32(W1.Substring(0, 2));
            int CR1 = Convert.ToInt32(W1.Substring(2, 2));
            int ST2 = Convert.ToInt32(W2.Substring(0, 2));
            int CR2 = Convert.ToInt32(W2.Substring(2, 2));
            int STDistance, CRMin, CRMax, CRMod;

            STDistance = Math.Abs(ST1 - ST2);

            int CROffset = (STDistance / 2);

            int mod1 = ST1 % 2;
            int mod2 = ST2 % 2;
            if (mod1 == 1 & mod2 == 0)
                CROffset++;

            CRMin = CR1 - CROffset;
            CRMax = CRMin + STDistance;

            CRMod = 0;
            if (CR2 < CRMin)
                CRMod = CRMin - CR2;
            if (CR2 > CRMax)
                CRMod = CR2 - CRMax;

            STDistance += CRMod;

            return STDistance;
        }
 
I think I actually got it from the traveler map site. If you look over his API's and stuff he had directions for all kinds of fun stuff in there.

And quite welcome!
 
Back
Top