Home > Java, Useful stuff > Find the point at which 2 lines intersect

Find the point at which 2 lines intersect

Given two lines ( defined as 2 x,y coordinates in an array ), this will return the x,y position at which the two lines intersect. If they do not intersect, it will return null.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public Coordinate intersects(Coordinate[] coA,Coordinate[] coB ) {
 
        double x11 = coA[0].getX();
        double y11 = coA[0].getY();
        double x12 = coA[1].getX();
        double y12 = coA[1].getY();
        double x21 = coB[0].getX();
        double y21 = coB[0].getY();
        double x22 = coB[1].getX();
        double y22 = coB[1].getY();
 
        double dx1 = x12 - x11;
        double dy1 = y12 - y11;
        double dx2 = x22 - x21;
        double dy2 = y22 - y21;
        double det = (dx2*dy1-dy2*dx1);
 
        Coordinate coReturn = null;
 
        if (det != 0.0) {
            double mu = ((x11 - x21)*dy1 - (y11 - y21)*dx1)/det;
            if (mu >= 0.0  &&  mu <= 1.0) {
                coReturn = new Coordinate();
                coReturn.setX((int)(x21 + mu*dx2 + 0.5));
                coReturn.setY((int)(y21 + mu*dy2 + 0.5));
            }
        }    
        return coReturn;
}
[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Google] [StumbleUpon]

Java, Useful stuff

  1. No comments yet.
  1. No trackbacks yet.