   Distance between two rects
  Hello there,I am wanting to create a function to (as efficiently as possible) determine the minimum distance between two rectangles' borders, each given as xmin, ymin, xmax, and ymax. I want the minimum distance from any point on the border of one rect to the closest point on the border of the other rect. (i.e. not center-to-center distances)Is there a clever algorithm for this? I'm looking to incorporate it into a nearest-neighbor search for my R-Tree.Also: since I'm going to be using this for comparison only, I can use the squared distance.   
  If they're axis-aligned just draw a picture of 2 rectangles on paper. You'll quickly see there are 8 possible outcomes (if they aren't inside one another). 4 of them just use a single distance check to the vertices. The other ones will result in things like object2.maxX - object1.minX. You can quickly just write:if(object1.maxX < object2.minX){ // Object 1 is on the left side of object 2  if(object1.maxY < object2.minY)  { // Object 1 is in the top left corner    return // distance from object1's bottom right vert to object2's top left  }  else if(object1.minY > object2.maxY)  { // Object 1 is in the bottom left corner    return // distance from object1's top right vert to object2's bottom left  }  else  { // Object 1 is in the middle left    return object2.minX - object1.maxX;  }}else if(object1.minX > object2.maxX){ // Object 1 is on the right side of object 2  etc...}else{  etc...}I think you see where I'm going. That one has a few short circuits. I can't think of another algorithm off the top of my head.   ;  Thanks for the help! I ended up doing this, after sitting/thinking about it a while. Thought it might be helpful if anyone else is doing this problem:#define __min(a,b)  (((a) < (b)) ? (a) : (b))#define __max(a,b)  (((a) > (b)) ? (a) : (b))double MinDistSqrd(Rect rectA, Rect rectB){  double squared[NUMDIMS];  double cSquared = 0;  for(int index=0; index < NUMDIMS; ++index)  {    squared[index] = (__max(rectA->min[index],rectB->min[index]) - __min(rectA->max[index],rectB->max[index]));    if(squared[index] > 0)    { cSquared += squared[index] * squared[index];    }  }  return cSquared;};NUMDIMS being 2 for rectangles, obviously. It's templated for my R-Tree.This shouuuuld end up as the positive min distance between the borders of rectA and rectB (where min and max are arrays of xmin, ymin, and xmax, ymax) - or 0 if they're overlapping.If I made an error though do let me know. :Xedit: included macro definitions in case you (like me) don't have them   