# Circle Collisions

A Circle to Circle collision detection algorithm.

Ian Mallett
(geometrian)
I've been working on this a while. Circles bounce off of each other correctly (I think...). Like my Gravity Simulation, the screenshot cannot convey what this program actually does. Download it and enjoy!

### Changes

http://geometrian.com/programming/index.php

### Releases

• #### Idteller 2011-10-15 06:09:07

Nice code. I recommend defining your screen, or surface as stated below;
SCREEN_WIDTH = 800SCREEN_HEIGHT = 600SCREEN_HEIGHT = 600screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
Then whenever you refer to the screen height or width you can do so by entering;
screen.get_width() or screen.get_height()This will allow you to modify the screen size if necessary without browsing through code for all screen width and height values. Instead you can just change the screen size at the beginning.

• #### Patric 2014-07-24 12:35:09

if Circle != Circle2:
Aren't you actually checking the circles with lower indices twice with this approach? My approach in a small game I recently wrote, was to go by the indices of the circles:
for n in range(len(Circles)):
# The whole code before the collision detection
if n < len(Circles) - 1:
if Circles[n].radius + Circles[n + 1].radius < math.hypot(Circles[n].x - Circles[n + 1].x, Circles[n].y - Circles[n + 1].y):
CircleCollide(Circles[n], Circles[n + 1])

What are your thoughts on this?

Pat

• #### Named Tuple 2014-07-25 14:17:24

I think he is checking the same circle pairs twice. Going by the indices works, but I think your approach misses non-adjacent circles in the list, i.e. circle 1 and circle 3 won't be checked. A solution is to use the python itertools library as below:

import itertools
for circle1, circle2 in itertools.combinations(range(20), 2):
#check for circle collision
# if circle collision:
# update circle velocity

Hope this helps! I am making something like this as well right now, maybe I will upload it at some point.

• #### hanna hansen 2020-04-24 18:47:18.951015

I really liked your code! in your function collision_detection you've written : Xdiff =-(C1.x-C2.x) and Ydiff = -(C1.y-C2.y). What is the purpose of minus(-) in front of the paranthesis?

#### hanna hansen 2020-04-24 18:54:24.002221

I also don't get why you are switching between radians and degrees while calculating which direction the balls should move if they collide. Is there a purpose behind doing so?