# Get radial distance between vector1 and vector2

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);
}

• What do you mean by "radial distance"? – 200_success Oct 23 '15 at 15:53
• Well regularly it refers to the euclidean vector but in this case.. a radius. – Malina Oct 23 '15 at 15:58
• Does this code give the intended results? – 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);
}

• 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. – Malina Oct 23 '15 at 16:05
• Note: double diffX = entity1.X; diffX -= entity2.X; costs 1 more int/double conversion, but prevents int overflow. – chux - Reinstate Monica Oct 28 '15 at 21:52
• @chux not really more int->double conversion because hypot takes 2 doubles and the params get converted before the function gets called – ratchet freak Oct 28 '15 at 22:03
• 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. – chux - Reinstate Monica Oct 28 '15 at 22:06