intersectSegmentCircleDisplace does not work when the segment is partially inside the circle
See original GitHub issueIssue details
The Intersector.intersectSegmentCircleDisplace() function is wrong when one of the endpoint of the segment is inside the circle.
The current algorithm calcultates the projection of the circle center on the infinite line (start, end), but returns no intersection if the projection point is not within the segment endpoints (as in the diagram above)
Also, the function is supposed to “returns by how much and in what direction the line has to move away from the circle to not intersect.” but it returns by how much and in what direction the line has to move to cross the circle center.
Here’s my correction:
public static float intersectSegmentCircleDisplace(Vector2 start, Vector2 end, Vector2 point, float radius, Vector2 displacement) {
float u = (point.x - start.x) * (end.x - start.x) + (point.y - start.y) * (end.y - start.y);
float d = start.dst(end);
u /= d * d;
if (u < 0)
tmp2.set(start);
else if (u > 1)
tmp2.set(end);
else {
tmp.set(end.x, end.y).sub(start.x, start.y);
tmp2.set(start.x, start.y).add(tmp.scl(u));
}
d = tmp2.dst(point.x, point.y);
if (d < radius) {
displacement.set(tmp2).sub(point).nor();
return radius - d;
} else
return Float.POSITIVE_INFINITY;
}
Reproduction steps/code
System.out.println(Intersector.intersectSegmentCircleDisplace(new Vector2(0,0), new Vector2(0,1), new Vector2(0,2),1.5f, new Vector2()));
returns Infinity instead of 0.5
Version of LibGDX and/or relevant dependencies
1.9.6
Please select the affected platforms
- Android
- iOS (robovm)
- iOS (MOE)
- HTML/GWT
- Windows
- Linux
- MacOS
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (5 by maintainers)
Wow! I guess nobody has ever used this one, it’s pretty bad. The implementation of intersectSegmentCircleDisplace is wrong but I believe it should be aligned with the intersectSegmentCircle implementation which is correct and more efficient:
On a more general note I see several things that could be improved:
I’ll work on a PR see where it goes that includes a fix for this.
@anigart Thank you, it’s been fixed