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

前端 未结 12 752
执念已碎
执念已碎 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 07:44

    You could also create a rectangle out of the segment and test if the other rectangle collides with it, since it is just a series of comparisons. From pygame source:

    def _rect_collide(a, b):
        return a.x + a.w > b.x and b.x + b.w > a.x and \
               a.y + a.h > b.y and b.y + b.h > a.y
    

提交回复
热议问题