以下代码具有2个功能。 (感谢@AlexRudenko谁帮助了我)
他们都得到一个段,一条线(不一定是不定式的)。除了他们已经拥有的那个。
第一个函数检查是否有一个交点(只有一个),并返回一个布尔值。
第二个应该检查相同并返回点本身。
// Returns true if the lines intersect, false otherwise
public boolean isIntersecting(Line other) {
if (equals(other)){
return false;
}
double x11 = this.start.getX();
double y11 = this.start.getY();
double x12 = this.end.getX();
double y12 = this.end.getY();
double x21 = other.start.getX();
double y21 = other.start.getY();
double x22 = other.end.getX();
double y22 = other.end.getY();
if (x11 == x12 && x21 == x22) { // both lines are constant x
// no intersection point
return false;
} else if (x11 == x12 || x21 == x22) { // either line is constant x
double x;
double m;
double b;
if (x11 == x12) { // first line is constant x, second is sloped
x = x11;
m = (y22 - y21) / (x22 - x21);
b = (x22 * y21 - x21 * y22) / (x22 - x21);
} else { // second line is constant x, first is sloped
x = x21;
m = (y12 - y11) / (x12 - x11);
b = (x12 * y11 - x11 * y12) / (x12 - x11);
}
double y = m * x + b;
Point.intersection = new Point (x,y);
return true;
} else { // both lines are sloped
double m1 = (y12 - y11) / (x12 - x11);
double b1 = (x12 * y11 - x11 * y12) / (x12 - x11);
double m2 = (y22 - y21) / (x22 - x21);
double b2 = (x22 * y21 - x21 * y22) / (x22 - x21);
if ((long) m1 == (long) m2) {
// no intersection point
return false;
}
// calculating intersection coordinates
double x = (b2 - b1)/(m1 - m2);
double y = m1 * x + b1; // or m2 * x + b2
Point.intersection = new Point (x,y);
return true;
}
}
// Returns the intersection point if the lines intersect,
// and null otherwise.
public Point intersectionWith(Line other) {
if (isIntersecting(other)) {
return Point.intersection;
}
return null;
}
我考虑过在第一个函数中将点“保存”在返回“真”值之前,然后使用此静态变量在第二个函数中“拉”该点并返回它的值。
另外,您是否认为关于段而不是不定式线,我应该为第一个功能添加更多条件?
我的意思是,可以说两者具有相同的斜率,但这并不意味着它们不能只有一个交点。因为如果我们在谈论
第1行:(1,0)(1,2)
和第2行:(1,2)(1,3)
它们都具有相同的斜率,但它们的交点仍为(1,2)。
那么,您认为我应该添加到代码中以消除所有这些情况吗?
我想到了类似的东西:
if(!this.start().equals(line.start())
||!this.start().equals(line.end())
||!this.end().equals(line.start())
||!this.end().equals(line.end()))
return false;
我想我还应该添加一个小检查,以检查交叉点是否在两个线段上。我应该获取交点的X和Y值,并检查X值是否在起点X值和终点X值之间(在两个线段上),并对Y值进行相同的检查。
你怎么看?
谢谢。
最佳答案
用tho来反之更容易吗?
public Point isIntersecting(Line other) {
//your calculation here
return Point
}
public Boolean intersectionWith(Line other) {
Point p=isIntersecting(other)
if(p==null)
return false
return true
}