import java.awt.*;
public class LineCrossing
{
double Ax, Bx, Cx, Dx, Px, Ay, By, Cy, Dy, Py, d1x, d2x, d1y, d2y;
public LineCrossing(Point A, Point B, Point C, Point D)
{
Ax = A.getX(); Ay = A.getY();
Bx = B.getX(); By = B.getY(); d1x = Bx - Ax; d1y = By - Ay;
Cx = C.getX(); Cy = C.getY();
Dx = D.getX(); Dy = D.getY(); d2x = Dx - Cx; d2y = Dy - Cy;
}
// returns true if the lines AB and CD cross
public boolean LinesCross()
{
boolean result = false;
crossingPoint();
// ^ is exclusive or - e.g. either Px is less than Ax or Bx but not both
boolean xABok = (Px < Ax) ^ (Px < Bx ); // Px is between Ax and Bx
boolean xCDok = (Px < Cx) ^ (Px < Dx ); // Py is between Ay and By
boolean yABok = (Py < Ay) ^ (Py < By ); // Px is between Cx and Dx
boolean yCDok = (Py < Cy) ^ (Py < Dy ); // Py is between Cy and Dy
result = xABok && xCDok && yABok && yCDok ;
return result;
}
// sets Px, Py to the crossing point of the two lines
// it works by getting P to be on both lines
// if they're parallel it still works, but returns infinity
public void crossingPoint( )
{
double denom = d1x * d2y - d2x * d1y;
Py = ((Cx*Dy-Cy*Dx)*d1y - (Ax*By - Ay*Bx)*d2y)/denom;
Px = ((Cx*Dy-Cy*Dx)*d1x - (Ax*By - Ay*Bx)*d2x)/denom;
System.out.println(" " + Px + ", " + Py);
}
}
java 图形编程常用的,检验两条直线是否相交的java算法.zip
版权申诉
137 浏览量
2023-01-31
16:21:43
上传
评论
收藏 6KB ZIP 举报
GZM888888
- 粉丝: 121
- 资源: 2902