How to test if a line segment intersects an axis-aligned rectange in 2D?

前端 未结 12 760
执念已碎
执念已碎 2020-11-30 07:33

How to test if a line segment intersects an axis-aligned rectange in 2D? The segment is defined with its two ends: p1, p2. The rectangle is defined with top-left and bottom-

12条回答
  •  鱼传尺愫
    2020-11-30 08:04

    Use the Cohen-Sutherland algorithm.

    It's used for clipping but can be slightly tweaked for this task. It divides 2D space up into a tic-tac-toe board with your rectangle as the "center square".
    then it checks to see which of the nine regions each of your line's two points are in.

    • If both points are left, right, top, or bottom, you trivially reject.
    • If either point is inside, you trivially accept.
    • In the rare remaining cases you can do the math to intersect with whichever sides of the rectangle are possible to intersect with, based on which regions they're in.

提交回复
热议问题