Skip to main content
 首页 » 编程设计

Python 碰撞检测,不在 pygame 中

2025年05月04日8lori

我正尝试在 Zelle 的 python 图形模块中构建二维 map 。 我使用 Polygon 类对象创建了 map 边界。 如果我想检查一个 cirlce 对象是否正在接触 map 边界以检测碰撞, 我该怎么办?

这是我的意思的一个例子:

poly  = Polygon(Point(x1,y1), Point(x2,y2), Point(x3,y3)) .draw(win)  # a triangle shape 
circ = Circle (Point(x4,y4), radius) .draw(win)      # drawn in the middle of the triangle map 

我可以使用 circ.getCenter() 获取 circ 位置,但我不知道检查两个对象是否交叉的最佳方法是什么.也许是这样的

def collision(circ,poly,x,y): 
 
    if position of circle passes the position of the line of the poly at x,y: 
        detect collision 
 
   else: 
       pass 

请您参考如下方法:

我想出了一个用 python 编写的碰撞检测程序,就在这里。

if circle_x < rect_x + circle_width and circle_x + rect_width > rect_x and circle_y < rect_y + circle_height and circle_height + circle_y > rect_height : 

但是,如果圆的边缘接触到矩形,这会感应到,因此为了让它感应圆是否接触到 map ,您需要将所有 rect_x 替换为 0,将所有 rect_y 替换为 0,然后将 rect_width 替换为屏幕宽度,将 rect_height 替换为屏幕高度,如下所示:

if circle_x < 0 + circle_width and circle_x + screen_width > 0 and circle_y < 0 + circle_height and circle_height + circle_y > screen_height : 

现在它通常会感知圆圈是否接触 map ,为了感知圆圈是否接触屏幕边缘,您不需要在其中添加任何内容if 语句并在您放置所需内容的地方制作 else 语句,如下所示:

if circle_x < 0 + circle_width and circle_x + screen_width > 0 and circle_y < 0 + circle_height and circle_height + circle_y > screen_height : 
    #put nothing here 
else: 
    #put the code you need here