Calculates the intersection location of the two lines formed by (x1, y1), (x2, y2) and (x3, y3), (x4, y4). - Java java.lang

Java examples for java.lang:Math Geometry Line

Description

Calculates the intersection location of the two lines formed by (x1, y1), (x2, y2) and (x3, y3), (x4, y4).

Demo Code

/*/*  w  w w  . ja  v a2 s  .c o m*/
 * Copyright (c) JenSoft API
 * This source file is part of JenSoft API, All rights reserved.
 * JENSOFT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
//package com.java2s;

public class Main {
    public static final Object PARALLEL = new Object();
    public static final Object INTERSECT = new Object();

    /**
     * Calculates the intersection location of the two lines formed by (x1, y1),
     * (x2, y2) and (x3, y3), (x4, y4). If the lines are determined to be
     * parallel, then Geom.PARALLEL is returned and no further computations are
     * done. If the lines are not parallel, then the intersection location is
     * stored in index locations 0 and 1 of the specified array. The parametric
     * value is stored in index location 2. If there is an intersection then the
     * returned value is Geom.INTERSECT.
     */
    public static Object getLineLineIntersection(double x1, double y1,
            double x2, double y2, double x3, double y3, double x4,
            double y4, double[] result) {
        double bx = x2 - x1;
        double by = y2 - y1;
        double dx = x4 - x3;
        double dy = y4 - y3;

        double b_dot_d_perp = bx * dy - by * dx;

        if (b_dot_d_perp == 0) {
            return PARALLEL;
        }

        double cx = x3 - x1;
        double cy = y3 - y1;

        double t = (cx * dy - cy * dx) / b_dot_d_perp;

        if (result != null) {
            result[0] = x1 + t * bx;
            result[1] = y1 + t * by;
            result[2] = t;
        }

        return INTERSECT;
    }
}

Related Tutorials