A small script to calculate total units of distance between two vector entities. Especially useful in games and grid snaps, inventory snaps etc..

typedef struct COORD
    int X, Y;
} coord;

int get_dist (coord entity1, coord entity2)
    int minuendX    = max(entity1.X, entity2.X);
    int minuendY    = max(entity2.Y, entity2.Y);
    int subtrahendX = min(entity1.X, entity2.X);
    int subtrahendY = min(entity2.Y, entity2.Y);

    return (minuendX - subtrahendX) + (minuendY - subtrahendY);
  • \$\begingroup\$ What do you mean by "radial distance"? \$\endgroup\$ – 200_success Oct 23 '15 at 15:53
  • \$\begingroup\$ Well regularly it refers to the euclidean vector but in this case.. a radius. \$\endgroup\$ – Malina Oct 23 '15 at 15:58
  • 1
    \$\begingroup\$ Does this code give the intended results? \$\endgroup\$ – 200_success Oct 23 '15 at 16:02

There is a typo in the y components, both times only entity2 is used. I believe that is a copy-paste error.

Your distance is better known as the manhattan distance. I suggest naming the method after it to avoid surprises.

An other method of getting it uses the absolute value of the differences:

int get_manhattan_dist (coord entity1, coord entity2)
    return abs(entity1.X - entity2.X) + abs(entity1.Y - entity2.Y);

Of course if you have the manhattan distance you can easily provide the euclidean distance

double get_euclid_dist (coord entity1, coord entity2)
    double diffX    = entity1.X - entity2.X;
    double diffY    = entity1.Y - entity2.Y;

    return hypot(diffX, diffY);
  • \$\begingroup\$ Oh you are right about the typos. I re-created my code in here. I am testing on the correct version though. Thank you, didn't know of its name. \$\endgroup\$ – Malina Oct 23 '15 at 16:05
  • \$\begingroup\$ Note: double diffX = entity1.X; diffX -= entity2.X; costs 1 more int/double conversion, but prevents int overflow. \$\endgroup\$ – chux - Reinstate Monica Oct 28 '15 at 21:52
  • \$\begingroup\$ @chux not really more int->double conversion because hypot takes 2 doubles and the params get converted before the function gets called \$\endgroup\$ – ratchet freak Oct 28 '15 at 22:03
  • \$\begingroup\$ double diffX = entity1.X - entity2.X; employs 1 int/double conversion. double diffX = entity1.X; diffX -= entity2.X; uses 2 int/double conversions. The call of hypot() does not affect that count. \$\endgroup\$ – chux - Reinstate Monica Oct 28 '15 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.