Java Rectangle Intersect intersects(Point p1, Point p2, Rectangle rect)

Here you can find the source of intersects(Point p1, Point p2, Rectangle rect)

Description

intersects

License

Open Source License

Declaration

static public boolean intersects(Point p1, Point p2, Rectangle rect) 

Method Source Code


//package com.java2s;
import java.awt.*;

public class Main {
    static public boolean intersects(Point p1, Point p2, Rectangle rect) {

        // top edge
        if (intersects(p1, p2, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y)))
            return true;

        // bottom edge
        if (intersects(p1, p2, new Point(rect.x, rect.y + rect.height),
                new Point(rect.x + rect.width, rect.y + rect.height)))
            return true;

        // left edge
        if (intersects(p1, p2, new Point(rect.x, rect.y), new Point(rect.x, rect.y + rect.height)))
            return true;

        // right edge
        if (intersects(p1, p2, new Point(rect.x + rect.width, rect.y),
                new Point(rect.x + rect.width, rect.y + rect.height)))
            return true;

        return false;
    }// w w w. ja  v a  2  s  .  c  o  m

    static public boolean intersects(Point p1, Point p2, Point p3, Point p4) {
        double ua = (double) ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x))
                / ((p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y));
        double ub = (double) ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x))
                / ((p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y));

        if (ua > 0 && ua < 1 && ub > 0 && ub < 1)
            return true;

        return false;
    }
}

Related

  1. intersects(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)
  2. intersects(final float x, final float y, final float z, final int sx, final int sy, final int sz)
  3. intersects(final Rectangle elementRect, final Rectangle viewportRect)
  4. intersects(final Rectangle2D a, final Rectangle2D b)
  5. intersects(float cx, float cy, float radius, float left, float top, float right, float bottom)
  6. intersects(Rectangle aRectangle, Line2D aLine)
  7. intersects(Rectangle rect1, Rectangle rect2, boolean vertical)
  8. intersects(Rectangle2D r, Object o)
  9. intersects(Rectangle2D rect1, Rectangle2D rect2)