首页 文章

Pygame的;检查两个矩形上任意点之间的最短距离是否小于x量?

提问于
浏览
0

基本上我正在制作一个带有pygame的游戏,并且会在屏幕上移动矩形 . 玩家1和玩家2 . 如果玩家1的任何单位在玩家2的单位的x距离内,则开火 . 如果我与中心保持距离,那么它将不准确,因为这些矩形中的一些将在一侧长得多并且将在被射击的范围内但是中心将不会 . 我一直在寻找,但一直无法找到解决这个问题的方法 .

编辑:删除了圈子 . 我也会有圈子,但我会像矩形一样对待它们并使用它们.rect . 它们很小,2像素不准确无关紧要 .

1 回答

  • 0

    这是我现在能想到的最好的:它将矩形的角与圆的中心进行比较 . 如果这还不够,您可以沿矩形边添加中心点 .

    不是一个完美的解决方案,但根据您正在编写的游戏,它应该足够了

    def isInRange(rectangle, circle):
        return (
            (rectangle.topleft.x     - circle.centerx)**2 + (rectangle.topleft.y     - circle.centery)**2 <= (mindist + r_circle)**2 or #circle in upper  left  quadrant of rectangle
            (rectangle.bottomleft.x  - circle.centerx)**2 + (rectangle.bottomleft.y  - circle.centery)**2 <= (mindist + r_circle)**2 or #circle in bottom left  quadrant of rectangle
            (rectangle.bottomright.x - circle.centerx)**2 + (rectangle.bottomright.y - circle.centery)**2 <= (mindist + r_circle)**2 or #circle in bottom right quadrant of rectangle
            (rectangle.topright.x    - circle.centerx)**2 + (rectangle.topright.y    - circle.centery)**2 <= (mindist + r_circle)**2    #circle in top    right quadrant of rectangle
            )
    

相关问题