How to calculate distance between two rectangles? (Context: a game in Lua.)

后端 未结 8 1514
梦毁少年i
梦毁少年i 2020-12-15 17:53

Given two rectangles with x, y, width, height in pixels and a rotation value in degrees -- how do I calculate the closest distance of their outlines toward each other?

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 18:14

    Please check this for Java, it has the constraint all rectangles are parallel, it returns 0 for all intersecting rectangles:

       public static double findClosest(Rectangle rec1, Rectangle rec2) {
          double x1, x2, y1, y2;
          double w, h;
          if (rec1.x > rec2.x) {
             x1 = rec2.x; w = rec2.width; x2 = rec1.x;
          } else {
             x1 = rec1.x; w = rec1.width; x2 = rec2.x;
          }
          if (rec1.y > rec2.y) {
             y1 = rec2.y; h = rec2.height; y2 = rec1.y;
          } else {
             y1 = rec1.y; h = rec1.height; y2 = rec2.y;
          }
          double a = Math.max(0, x2 - x1 - w);
          double b = Math.max(0, y2 - y1 - h);
          return Math.sqrt(a*a+b*b);
       }
    

提交回复
热议问题