Compute the intersection of 2 lines described by a point and a vector. - Java java.lang

Java examples for java.lang:Math Vector

Description

Compute the intersection of 2 lines described by a point and a vector.

Demo Code


import javax.vecmath.Point2d;
import javax.vecmath.Tuple2d;
import javax.vecmath.Vector2d;

public class Main{
    /**//from w ww  .  j  a v a 2  s.c  o  m
     * Compute the intersection of 2 lines described by a point and a vector.
     * If there is no or infinite number of intersection, returns null
     * @param p1 first line point
     * @param v1 first line vector
     * @param p2 second line point
     * @param v2 second line vector
     * @return the intersection point or null if lines are quite parallel
     */
    public static Point2d intersectionPoint(final Point2d p1,
            final Vector2d v1, final Point2d p2, final Vector2d v2) {
        return intersectionPoint(p1, v1, p2, v2, MathUtil.epsilon);
    }
    /**
     * Compute the intersection of 2 lines described by a point and a vector.
     * If there is no or infinite number of intersection, returns null
     * @param p1 first line point
     * @param v1 first line vector
     * @param p2 second line point
     * @param v2 second line vector
     * @param epsilon min value of the dot product v1.v2 which tells if lines are intersecting or not
     * @return the intersection point or null if lines are quite parallel
     */
    public static Point2d intersectionPoint(final Point2d p1,
            final Vector2d v1, final Point2d p2, final Vector2d v2,
            final double epsilon) {
        double denom = cross(v1, v2);
        if (isZero(denom, epsilon)) {
            return null;
        }
        double t2 = -((p2.y - p1.y) * v1.x - v1.y * (p2.x - p1.x)) / denom;
        return new Point2d(p2.x + t2 * v2.x, p2.y + t2 * v2.y);
    }
    /**
     * Compute the cross product between two vectors
     * @param v1 first vector
     * @param v2 second vector
     * @return v1x * v2y - v1y * v2x 
     */
    public static double cross(final Vector2d v1, final Vector2d v2) {
        return v1.x * v2.y - v1.y * v2.x;
    }
    /**
     * @return true if x is quite equal to zero ( -eps < x < eps)
     */
    public static boolean isZero(final double x, final double epsilon) {
        return Math.abs(x) < epsilon;
    }
}

Related Tutorials