public static boolean lineIntersection ( Point2D p1 , Point2D p2 , boolean seg1 , Point2D p3 , Point2D p4 , boolean seg2 , Point2D result ) { // see http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/ double y43 = p4 . getY ( ) - p3 . getY ( ) ; double x21 = p2 . getX ( ) - p1 . getX ( ) ; double x43 = p4 . getX ( ) - p3 . getX ( ) ; double y21 = p2 . getY ( ) - p1 . getY ( ) ; double denom = y43 * x21 - x43 * y21 ; if ( denom == 0 ) { return false ; } double y13 = p1 . getY ( ) - p3 . getY ( ) ; double x13 = p1 . getX ( ) - p3 . getX ( ) ; double ua = ( x43 * y13 - y43 * x13 ) / denom ; if ( seg1 && ( ( ua < 0 ) || ( ua > 1 ) ) ) { return false ; } if ( seg2 ) { double ub = ( x21 * y13 - y21 * x13 ) / denom ; if ( ( ub < 0 ) || ( ub > 1 ) ) { return false ; } } double x = p1 . getX ( ) + ua * x21 ; double y = p1 . getY ( ) + ua * y21 ; result . setLocation ( x , y ) ; return true ; }
Calculate the intersection of two lines . Either line may be considered as a line segment and the intersecting point is only considered valid if it lies upon the segment . Note that Point extends Point2D .