Checks whether line (x1, y1) - (x2, y2) and line (x3, y3) - (x4, y4) intersect. - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

Checks whether line (x1, y1) - (x2, y2) and line (x3, y3) - (x4, y4) intersect.

Demo Code



public class Main{
    public static final float EPSILON = FloatMath.pow(10, -14);
    /**/*from w  w  w  . jav  a  2 s .  c  o  m*/
     * Checks whether line (x1, y1) - (x2, y2) and line (x3, y3) - (x4, y4) intersect. If lines
     * intersect then the result parameters are saved to point array. The size of {@code point}
     * must be at least 2.
     *
     * @return 1 if two lines intersect in the defined interval, otherwise 0.
     */
    public static int intersectLines(float x1, float y1, float x2,
            float y2, float x3, float y3, float x4, float y4, float[] point) {
        float A1 = -(y2 - y1);
        float B1 = (x2 - x1);
        float C1 = x1 * y2 - x2 * y1;
        float A2 = -(y4 - y3);
        float B2 = (x4 - x3);
        float C2 = x3 * y4 - x4 * y3;
        float coefParallel = A1 * B2 - A2 * B1;
        // float comparison
        if (x3 == x4 && y3 == y4 && (A1 * x3 + B1 * y3 + C1 == 0)
                && (x3 >= Math.min(x1, x2)) && (x3 <= Math.max(x1, x2))
                && (y3 >= Math.min(y1, y2)) && (y3 <= Math.max(y1, y2))) {
            return 1;
        }
        if (Math.abs(coefParallel) < EPSILON) {
            return 0;
        }
        point[0] = (B1 * C2 - B2 * C1) / coefParallel;
        point[1] = (A2 * C1 - A1 * C2) / coefParallel;
        if (point[0] >= Math.min(x1, x2) && point[0] >= Math.min(x3, x4)
                && point[0] <= Math.max(x1, x2)
                && point[0] <= Math.max(x3, x4)
                && point[1] >= Math.min(y1, y2)
                && point[1] >= Math.min(y3, y4)
                && point[1] <= Math.max(y1, y2)
                && point[1] <= Math.max(y3, y4)) {
            return 1;
        }
        return 0;
    }
}

Related Tutorials