Java Rectangle rectDistance(final Rectangle r, final Rectangle q)

Here you can find the source of rectDistance(final Rectangle r, final Rectangle q)

Description

rect Distance

License

Apache License

Declaration

public static int rectDistance(final Rectangle r, final Rectangle q) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.awt.Rectangle;

public class Main {
    public static int rectDistance(final Rectangle r, final Rectangle q) {
        if (rectOverlaps(r, q)) {
            return 0;
        }//from ww  w  .j a  va  2  s  .c om

        int r_x0 = r.x;
        int r_x1 = r.x + r.width;
        int r_y0 = r.y;
        int r_y1 = r.y + r.height;

        int q_x0 = q.x;
        int q_x1 = q.x + q.width;
        int q_y0 = q.y;
        int q_y1 = q.y + q.height;

        int d = 0;
        if (r_x0 > q_x1) {
            d += (r_x0 - q_x1) * (r_x0 - q_x1);
        } else if (q_x0 > r_x1) {
            d += (q_x0 - r_x1) * (q_x0 - r_x1);
        }
        if (r_y0 > q_y1) {
            d += (r_y0 - q_y1) * (r_y0 - q_y1);
        } else if (q_y0 > r_y1) {
            d += (q_y0 - r_y1) * (q_y0 - r_y1);
        }
        return (int) Math.sqrt((double) d);
    }

    public static boolean rectOverlaps(final Rectangle r, final Rectangle q) {
        int x0 = r.x;
        int x1 = r.x + r.width;
        int y0 = r.y;
        int y1 = r.y + r.height;

        int q_x0 = q.x;
        int q_x1 = q.x + q.width;
        int q_y0 = q.y;
        int q_y1 = q.y + q.height;

        return x0 <= q_x1 && y0 <= q_y1 && q_x0 <= x1 && q_y0 <= y1;
    }
}

Related

  1. normalizeRect(Rectangle rect)
  2. randomRectangle(int minW, int maxW, int minH, int maxH)
  3. randomSquare(int minW, int maxW)
  4. rectangleResize(Rectangle rect, int width, int height)
  5. rectCollide(final Rectangle a, final Rectangle b)
  6. rectFromArray(Rectangle2D aRectangle, double[] pts)
  7. rectFromRect2D(Rectangle2D rect)
  8. resetPosition(Window window1, Window window2)
  9. right(Rectangle r)