2014-03-03 107 views
2

我正在做碰撞检测程序在我的光标是用20的半径的圆,当它击中另一个圆的值应更改为TRUE。出于测试目的,我在屏幕中心有一个半径为50的固定圆。我能够测试光标圆是否已经碰到固定圆,但是它不能正常工作,因为它实际上测试它是否正常击中一个正方形而不是一个圆圈。数学不好,我一直无法找到答案。我已经找到了如何测试光标是否触摸它,但从来没有两个具有两个不同半径的对象。pygame的 - 碰撞检测与两个圆

如何检查两个圆圈之间的碰撞?谢谢!

这里是我的代码:

#@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() 

回答

10

只需选中两个中心之间的距离是否小于半径的总和。想象一下,两个圆圈之间几乎没有碰触(见下图),然后在两个中心之间划一条线。该线的长度将是两个半径的总和(或者如果您是拉丁文,则为半径)。因此,如果两个圆相交,它们中心之间的距离将小于半径的总和,如果它们不相交,则将大于总和。

enter image description here

+3

我设法做到了!任何有兴趣: 如果(m.sqrt((MX-X)** 2 +(MY-Y)** 2)<=半径+ cursorRadius): 我只是做两点之间的距离,就像你说的。 –