Pygame - 两个圆形的碰撞检测

7
我正在制作一个碰撞检测程序,其中我的光标是半径为20的圆形,并且当它击中另一个圆时应将值更改为TRUE。出于测试目的,我在屏幕中心放置了一个半径为50的静止圆。我能够测试光标圆是否撞到静止圆,但它并不完全正常工作,因为它实际上是在测试是否撞到了一个正方形而不是圆形。我不太擅长数学,也找不到答案。我已经找到了如何测试光标是否触摸它,但从未找到过两个具有不同半径的对象之间的解决方法。
如何检查两个圆之间的碰撞?谢谢!
以下是我的代码:
#@PydevCodeAnalysisIgnore
#@UndefinedVariable
import pygame as p, sys, random as r, math as m
from pygame.locals import *
from colour import *

p.init()

w,h=300,300
display = p.display.set_mode([w,h])
p.display.set_caption("Collision Test")
font = p.font.SysFont("calibri", 12)

x,y=150,150
radius=50
cursorRadius=20
count=0
hit=False

while(True):
    display.fill([0,0,0])
    mx,my=p.mouse.get_pos()
    for event in p.event.get():
        if(event.type==QUIT or (event.type==KEYDOWN and event.key==K_ESCAPE)):
            p.quit()

    ### MAIN TEST FOR COLLISION ###
    if(mx in range(x-radius,x+radius) and my in range(y-radius,y+radius)):
        hit=True
    else:
        hit=False

    p.draw.circle(display,colour("blue"),[x,y],radius,0)
    p.draw.circle(display,colour("white"),p.mouse.get_pos(),cursorRadius,0)

    xy=font.render(str(p.mouse.get_pos()),True,colour("white"))
    hitTxt=font.render(str(hit),True,colour("white"))
    display.blit(xy,[5,285])
    display.blit(hitTxt,[270,285])

    p.display.update()
1个回答

21

只需检查两个圆心之间的距离是否小于半径之和即可。 想象一下两个圆刚好相互接触(见下图),然后在两个圆心之间画一条直线。 该行的长度将是两个半径的总和(如果您使用拉丁语,则是半径)。 因此,如果两个圆相交,则它们的中心之间的距离将小于半径之和,如果它们不相交,则该距离将大于半径之和。

enter image description here


5
我做到了!对于任何感兴趣的人: 如果(m.sqrt((mx-x)**2+(my-y)**2)<=radius+cursorRadius): 我只需要按照你说的计算两点之间的距离。 - undefined
谢谢,你们字面编程之神为我们节省了时间。 - colappse
令人印象深刻而简洁,完美无瑕。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接