How to know if a line intersects a rectangle

后端 未结 8 543
梦谈多话
梦谈多话 2020-12-01 14:51

I have checked out this question, but the answer is very large for me:

How to know if a line intersects a plane in C#? - Basic 2D geometry

Is there any .NET

8条回答
  •  有刺的猬
    2020-12-01 15:02

    The simplest computational geometry technique is to just walk through the segments of the polygon and see if it intersects with any of them, as it then must also intersect the polygon.

    The only caveat of this method (and most of CG) is that we have to be careful about edge cases. What if the line crosses the rectangle at a point - do we count that as intersection or not? Be careful in your implementation.

    Edit: The typical tool for the line-intersects-segment calculation is a LeftOf(Ray, Point) test, which returns if the point is the to the left of the ray. Given a line l (which we use as a ray) and a segment containing points a and b, the line intersects the segment if one point is to the left and one point is not:

    (LeftOf(l,a) && !LeftOf(l,b)) || (LeftOf(l,b) && !LeftOf(l,a))
    

    Again, you need to watch out for edge-cases, when the point is on the line, but depends how you wish to actually define intersection.

提交回复
热议问题