Line2d implements GeometricObject, Cloneable { public IntersectionResult getIntersection( Line2d otherLine ) { double denom = ((otherLine.end.getY() - otherLine.begin.getY())*(end.getX() - begin.getX())) - ((otherLine.end.getX() - otherLine.begin.getX())*(end.getY() - begin.getY())); double numea = ((otherLine.end.getX() - otherLine.begin.getX())*(begin.getY() - otherLine.begin.getY())) - ((otherLine.end.getY() - otherLine.begin.getY())*(begin.getX() - otherLine.begin.getX())); double numeb = ((end.getX() - begin.getX())*(begin.getY() - otherLine.begin.getY())) - ((end.getY() - begin.getY())*(begin.getX() - otherLine.begin.getX())); if( denom == 0.0 ) { if( numea == 0.0 && numeb == 0.0 ) { return new IntersectionResult( IntersectionType.COINCIDENT ); } return new IntersectionResult( IntersectionType.PARALLEL ); } double ua = numea / denom; double ub = numeb / denom; if( ua >= 0.0 && ua <= 1.0 && ub >= 0.0 && ub <= 1.0 ) { double intX = begin.getX() + ua*(end.getX() - begin.getX() ); double intY = begin.getY() + ua*(end.getY() - begin.getY() ); return new IntersectionResult( new Point2dImpl( (float)intX, (float)intY ) ); } return new IntersectionResult( IntersectionType.NOT_INTERESECTING ); } Line2d();  Line2d(Point2d begin, Point2d end);  Line2d(float x1, float y1, float x2, float y2); void setBeginPoint(Point2d begin); void setEndPoint(Point2d end); Point2d getBeginPoint(); Point2d getEndPoint(); Point2d setEndPoint(); IntersectionResult getIntersection( Line2d otherLine ); Point2d reflectAroundLine( Point2d pointToReflect ); Line2d lineWithinSquare(Rectangle r); static double distance(Point2d p1, Point2d p2); static double distance(float p1x, float p1y, float p2x, float p2y); static Line2d lineFromRotation(int x1, int y1, double theta, int length); double calculateLength(); double calculateHorizontalAngle(); double calculateVerticalAngle(); @Override Line2d transform(Matrix transform); Line2d getNormal(); Line2d getNormal( Point2d p ); @Override void translate( float x, float y ); boolean isOnLine( Point2d p, float tolerance ); boolean isInLine( Point2d p, float tolerance ); @Override String toString(); @Override Rectangle calculateRegularBoundingBox(); @Override void scale(float sc); @Override void scale(Point2d centre, float sc); @Override void scaleCOG(float sc); @Override Point2d getCOG(); @Override double minX(); @Override double minY(); @Override double maxX(); @Override double maxY(); @Override double getWidth(); @Override double getHeight(); Point2dImpl toUnitVector(); @Override Line2d clone(); public Point2d begin; public Point2d end; }
@Test public void testIntersection() { Line2d line = new Line2d( new Point2dImpl(-2,0), new Point2dImpl(4,12) ); IntersectionResult result = line.getIntersection( new Line2d( new Point2dImpl(-4,8), new Point2dImpl(4,0) ) ); assertEquals(0, result.intersectionPoint.getX(), 0.001); assertEquals(4, result.intersectionPoint.getY(), 0.001); }