I'm making a collision detection program where my cursor is a circle with a radius of 20 and should change a value to TRUE when it hits another circle. For testing purposes, I have a stationary circle in the centre of my screen with a radius of 50. I'm able to test whether the cursor circle has hit the stationary circle but it doesn't quite work properly because it's actually testing if it's hitting a square rather than a circle. I'm not very good with maths and I haven't been able to find the answer to this. I've found how to test if the cursor is touching it but never two objects with two different radii.
How do I check for collision between two circles? Thanks!
Here's my code:
#@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()
Just check whether the distance between the two centers is less than the sum of the radiuses. Imagine the two circles just barely touching each other (see graphic below), then draw a line between the two centers. The length of that line will be sum of the two radiuses (or radii if you're Latin). So if the two circles intersect, the distance between their centers will be less than the sum of the radiuses, and if they don't intersect, it will be more than the sum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With