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 30 31
| /**
* Computes the intersection between two segments.
* @param x1 Starting point of Segment 1
* @param y1 Starting point of Segment 1
* @param x2 Ending point of Segment 1
* @param y2 Ending point of Segment 1
* @param x3 Starting point of Segment 2
* @param y3 Starting point of Segment 2
* @param x4 Ending point of Segment 2
* @param y4 Ending point of Segment 2
* @return Point where the segments intersect, or null if they don't
*/
public Point intersection(
int x1,int y1,int x2,int y2,
int x3, int y3, int x4,int y4) {
int d = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4);
if (d == 0) return null;
int xi = ((x3-x4)*(x1*y2-y1*x2)-(x1-x2)*(x3*y4-y3*x4))/d;
int yi = ((y3-y4)*(x1*y2-y1*x2)-(y1-y2)*(x3*y4-y3*x4))/d;
Point p = new Point(xi,yi);
if (xi < Math.min(x1,x2) || xi > Math.max(x1,x2)) return null;
if (xi < Math.min(x3,x4) || xi > Math.max(x3,x4)) return null;
return p;
} |
Partager