【问题标题】:How can I know if a circle and a rect is touched in Pygame?我怎么知道在 Pygame 中是否触摸了一个圆和一个矩形?
【发布时间】:2019-02-23 10:40:48
【问题描述】:

在我的程序中有一个圆和一个矩形在表面上移动。我想知道一个圆圈和一个矩形是否相互接触。它必须非常准确。很抱歉没有解释它的细节,但我希望你能理解。

【问题讨论】:

    标签: python pygame geometry rect


    【解决方案1】:

    考虑一个轴对齐的矩形由左上原点和宽度和高度给出:

    rect_tl   = (x, y)
    rect_size = (width, height)
    

    一个圆由一个中心点和一个半径给出:

    circle_cpt = (x, y)
    circle_rad = r
    

    如果要测试这两个形状是否重叠,则需要运行 2 次测试以捕获所有可能的情况。

    首先必须测试圆的中心点是否在矩形内。这可以通过pygame.Rect.collidepoint 轻松完成:

    rect = pygame.Rect(*rect_tl, *rect_size)
    isIsect = rect.collidepoint(*circle_cpt)
    

    此外,还必须测试矩形的any 角点是否在圆内。如果角点和圆的中心点之间的距离小于或等于圆的半径,就会出现这种情况。一个点可以用pygame.math.Vector2表示,两点之间的距离可以用pygame.math.Vector2.distance_to()得到:

    centerPt = pygame.math.Vector2(*circle_cpt)
    cornerPts = [rect.bottomleft, rect.bottomright, rect.topleft, rect.topright]
    isIsect = any([p for p in cornerPts if pygame.math.Vector2(*p).distance_to(centerPt) <= circle_rad])
    

    结合两个测试的函数可能如下所示:

    def isectRectCircle(rect_tl, rect_size, circle_cpt, circle_rad):
    
        rect = pygame.Rect(*rect_tl, *rect_size)
        if rect.collidepoint(*circle_cpt):
            return True
    
        centerPt = pygame.math.Vector2(*circle_cpt)
        cornerPts = [rect.bottomleft, rect.bottomright, rect.topleft, rect.topright]
        if [p for p in cornerPts if pygame.math.Vector2(*p).distance_to(centerPt) <= circle_rad]:
            return True
    
        return False
    

    【讨论】:

      猜你喜欢
      • 2012-09-27
      • 2011-11-23
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 2018-09-24
      • 2010-09-20
      • 1970-01-01
      相关资源
      最近更新 更多