An example code Rectangle and Line segment Intersection in ncollide2d


Most of the examples I see in the code are far too advanced for my needs.

I just wanted to get at most 2 points that a line segment intersects with the rectangle. I would appreciate if you can help me where to look?



Is your rectangle axis-aligned? If so, you can represent it as an AABB and then call aabb.clip_line to retrieve the intersection segment. (The endpoints of this segment will be the intersection points.)

1 Like

Thank you very much. I’ve been testing it, and it seems to cover most of my needs,
except for 2 cases:

  • when one of the endpoint is inside the AABB box, it tries to extend it like a ray returning 2 collision points. There should only be one collision point.
  • when the line segment is collinear with any side of the box, it returns a line segment with 0 length(ie: point.a = point.b), which is essentially 1 single point.

However, both of this edge case can be mitigates by making separate conditional branch and only use the aabb box line clipping for the rest of the cases.