I'm trying to make an agar.io-like game with pygame, for those who dont know, it's a game where you control a circle's movement with your cursor and eat other circle enemies to grow your size, Im new to python and I dont know much though, I figured out everything by myself for now but im stuck at the collision detection part, I want to create a function that returns true when it touches another circle. I tried searching for a solution but couldn't find any.
Asked
Active
Viewed 544 times
0
-
22 circles are intersecting, if the distance between the 2 center points is less than the sum of the 2 radii. – Rabbid76 Jun 11 '19 at 16:43
-
Instead of checking the raw distance between the two objects, instead check the *squared* distance. You can avoid the relatively costly call to `sqrt` this way. – PMende Jun 11 '19 at 16:56
1 Answers
1
2 circles are intersecting, if the distance between the 2 center points is less than the sum of the 2 radii. The distance between 2 points can be calculated by the Euclidean distance:
dist = math.sqrt(dx*dx + dy*dy)
In pygame this can be calculated by pygame.math.Vector2.distance_to()
.
If the 1st circle is defined by the center point (x1, y1)
and the radius radius1
and the 2nd circle is defined by the center point (x2, y2)
and the radius radius2
, then:
centerPoint1 = pygame.math.Vector2(x1, y1)
centerPoint2 = pygame.math.Vector2(x2, y2)
collide = centerPoint1.distance_to(centerPoint2) < (radius1 + radius2)
collide
is True
if the 2 circles are intersecting.
If you want to avoid the square root operation, then you can use distance_squared_to()
and compare the square of both lengths:
max_dist_square = (radius1 + radius2)*(radius1 + radius2)
collide = centerPoint1.distance_squared_to(centerPoint2) < max_dist_square

Rabbid76
- 202,892
- 27
- 131
- 174
-
Note: if you use [`Sprites`](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite), you can simply use the [`pygame.sprite.spritecollide()`](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_circle) function for this. – sloth Jun 12 '19 at 08:05