Algorithm defining the relationship between a square and a rectangle

I need to find an algorithm that determines the relationship between a square and a rectangle. He should be able to determine if:

  • The square is completely inside the rectangle
  • A square partially inside (overlaps) a rectangle
  • The square corner only touches the rectangle.
  • The square edge is on the edge of the rectangle

And here are the inputs (setpoints) that will help us extract the mathematical formula for each case:

  • x coordinate of the center of the square = squareX
  • y coordinate of the center of the square = squareY
  • square width = square W
  • x coordinate of the center of the rectangle = recX
  • y coordinate of the center of the rectangle = recY
  • rectangle width = recW
  • rectangle length = recL

PS: rectangles are always larger than square.

Java, , .

Edit:

, , , (Math.abs ):

((Math.abs(Math.abs(recX-squareX)-(recW+squareW)/2))<=0.001) && ((Math.abs(Math.abs(recY-squareY)-(recL+squareW)/2))<=0.001)
+3
2

double dx = Math.abs(rectX - squareX);
double dy = Math.abs(rectY - squarey);
double dw2 = (rectW + squareW) / 2;
double dh2 = (rectL + squareW) / 2;

if (Double.compare(dx, dw2) == 0 && Double.compare(dy, dh2) == 0)
    return CORNER_TOUCH;
else if (Double.compare(dx, dw2) > 0 || Double.compare(dy, dh2) > 0)
    return OUTSIDE;
else if (Double.compare(dx, dw2) == 0 || Double.compare(dy, dh2) == 0)
    return EDGE_TOUCH;
else if (Double.compare(dx, rectW - dw2) <= 0 &&
        Double.compare(dy, rectL - dh2) <= 0)
    return INSIDE;
else 
    return OVERLAPS;
+2
squareX1 = squareX - squareW/2
squareY1 = squareY - squareW/2
squareX2 = squareX + squareW/2
squareY2 = squareY + squareW/2

recX1 = recX - recW/2
recY1 = recY - recL/2
recX2 = recX + recW/2
recY2 = recY + recL/2

inside = squareX1 > recX1 && squareX2 < recX2 && squareY1 > recY1 && squareY2 < recY2
overlaps = squareX1 < recX2 && squareX2 > recX1 && squareY1 < recY2 && squareY2 > recY1

+1

Source: https://habr.com/ru/post/1790156/


All Articles