Reputation: 41
Why does this code:
Line2D line1 = new Line2D.Double(464.9298111721873, 103.78661133348942, 684.8391765253534, -155.44752172931908);
Line2D line2 = new Line2D.Double(414.16903384086487, 163.62456359144306, 393.52528378472925, 187.95988300984624);
line1.intersectsLine(line2);
return true?
Clearly, x coordinates of lines are way apart, and they do not intersect. I drew them onto a swing panel, and they are apart, but look like they are collinear. Is this the problem? I tried testing on simple collinear lines (like (1, 3, 4, 3), (6, 3, 8, 3)), and it seemes to work fine.
Upvotes: 4
Views: 618
Reputation: 35491
Java Docs say that the method of the Line2D
class:
public boolean intersects(double x, double y, double w, double h)
tests if the interior of the Shape
intersects the interior of a specified rectangular area. It uses the Shape.intersects()
method for this, however the calculations to accurately determine this intersection are very expensive.
This means that for some Shapes
this method might return true even though the rectangular area does not intersect the Shape
.
Although you are using the method itersectsLine()
, both intersects()
and intersectsLine()
use the same expensive method underneath the surface. The method is called linesIntersect()
and is specified here on line 298
The Area
class performs more accurate computations of geometric intersection than most Shape
objects and therefore can be used if a more precise answer is required. For instance:
boolean intersectionExists(Shape shape1, Shape shape2) {
Area area1 = new Area(shape1);
area1.intersect(new Area(shape2));
return !area1.isEmpty();
}
Tested using your values:
public static void main(String[] args) {
Line2D line1 = new Line2D.Double(464.9298111721873, 103.78661133348942, 684.8391765253534, -155.44752172931908);
Line2D line2 = new Line2D.Double(414.16903384086487, 163.62456359144306, 393.52528378472925, 187.95988300984624);
System.out.println("Lines intersect? " + intersectionExists(line1, line2));
}
Output:
Lines intersect? false
Upvotes: 2