Search code examples
pythonpygamecollision-detection

How to fix these circles' collision in pygame?


So, basically I want two circles to accelerate towards each other with acceleration 1. I want to stop when the circles collide. However, the code stops before they collide. This is because it calculates that in the next iteration, they pass right through. So it stops. How to improve this, so that it gives the required result. I have asked it to print the positions and velocity of circles so that u can look at the data when it runs. Thanks in advance.

import pygame
pygame.init()

w=1000
h=500
dis=pygame.display.set_mode((w,h))
pygame.display.set_caption("test2")

t=10
x1=50
x2=w-50
y1=250
y2=y1
v=0
r=True
def circles():
    pygame.draw.circle(dis,(0,200,0),(x1,y1),25)
    pygame.draw.circle(dis,(0,0,200),(x2,y2),25)

run=True
while run:
    pygame.time.delay(100)
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            run=False

    while r:
        pygame.time.delay(t)
        dis.fill((255,255,255))
        circles()
        print(x2,x1,(x2-x1),v,t)

        x1+=v
        x2-=v
        v+=1

        if x2-x1<=50: # THIS LINE STOPS  THE CIRCLES
            r=False

        pygame.display.update()
pygame.quit()

Solution

  • What you actually do is to draw the circles, then update there position and finally update the display.
    Change the order. Update the position of the circles, then draw them at there current position and finally update the display. So the circles are shown at there actual position.

    run=True
    while run:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                run=False
    
        pygame.time.delay(t)
    
        if r:
            x1 += v
            x2 -= v
            v += 1
    
            if x2-x1 <= 50: 
                r=False
    
        print(x2,x1,(x2-x1),v,t)
    
        dis.fill((255,255,255))
        circles()
        pygame.display.update()
    

    Furthermore, 1 loop is absolutely sufficient. Just verify if r: in the main application loop.

    If you don't want that the circles are intersecting at there final position, then you've to correct the positions:

    if x2-x1 <= 50: 
        r = False
        d = x2-x1
        x1 -= (50-d) // 2
        x2 += (50-d) // 2