我怎么知道在Pygame中是否碰到了一个圆和一个矩形

我怎么知道在Pygame中是否碰到了一个圆和一个矩形

本文介绍了我怎么知道在Pygame中是否碰到了一个圆和一个矩形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There is a circle and a rect moving on the surface in my program. I want to know if a circle and a rect is touched to each other. It had to be very accurate. I'm sorry for not explaining its detail, but I hope you understood.

推荐答案

考虑到轴对齐的矩形由左上角的原点以及宽度和高度给出:

Consider a axis aligned rectangle is given by a top left origin and a width and a height:

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

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

And a circle is given by a center point and a radius:

circle_cpt = (x, y)
circle_rad = r

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

If you want to test whether these two shapes overlap, you need to run 2 tests to capture all possible cases.

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

First it has to be tested if the center point of the circle is inside the rectangle. This can be done by pygame.Rect.collidepoint with ease:

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

此外,如果 any 矩形的角点位于圆内.如果圆的角点和圆心之间的距离小于或等于圆的半径,则为这种情况.可以通过 pygame.math.Vector2来表示一个点 ,两点之间的距离可以通过 pygame.math.Vector2.distance_to() :

Furthermore it has to be tested if any corner point of the rectangle is inside the circle. This is the case if the distance between a corner point and the center point of the circle is less than is or equal the radius of the circle. A point can be represented by pygame.math.Vector2 and the distance between 2 points can be get by 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])

结合了两个测试的函数可能看起来像这样:

A function which combines both tests may look like this:

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

这篇关于我怎么知道在Pygame中是否碰到了一个圆和一个矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:44