1

My goal is for my program to be able to detect collision when the ball sprite hits any one of the 'g_ball' sprites. The code apperently detects collision, and i have the "print" statement to test it...but it's CONSTANTLY printing "progress" even though none of the sprites are touching. Here is the code:

while 1:
    screen.blit(background, (0,0))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()


        if event.type == KEYDOWN:
            if event.key == K_a:
                m_x = -4
                s+=1
            elif event.key == K_d:
                m_x = +4
                s2+=1
        if event.type == KEYUP:
            if event.key == K_a:
                m_x = 0
            elif event.key == K_d:
                m_x = 0

    x+= m_x
    y+= m_y      

    ball = pygame.sprite.Sprite()
    ball.image = pygame.image.load('red_ball.png').convert()
    ball.rect = ball.image.get_rect()
    ball.image.set_colorkey((white))
    screen.blit(ball.image,(x,y))
    if x > 640:
        x = 0
    if x < 0:
        x = 640


    g_ball = pygame.sprite.Sprite()
    g_ball.image = pygame.image.load('green_ball.png').convert()
    g_ball.rect = g_ball.image.get_rect()
    g_ball.image.set_colorkey(white)
    screen.blit(g_ball.image,(50,t))
    t+=5
    if t > 521:
        t = 0
    collision = pygame.sprite.collide_rect(ball, g_ball)
    if collision == True:
        print ('PROGRESS!!!')
15H
  • 31
  • 2
  • 5

2 Answers2

0

It's because you have no offset set for the collision, you have only passed the offset to screen.blit.

Your fixed code would be this:

...
ball.rect = ball.image.get_rect()
ball.rect.topleft = (x, y)
...
g_ball.rect = g_ball.image.get_rect()
g_ball.rect.topleft = (50, t)
...
orlp
  • 112,504
  • 36
  • 218
  • 315
0

nightcracker is right. Do you realize what you are doing in this loop (which is supposed to run as fast as possible)? you are creating 2 new balls, you load the image from hd, you place them to (0,0), and then you print them manually on screen at a given position. This last part means you display them somewhere, but not where they really are (you did set their real position with ball.rect=ball.image.get_rect()). They really are at (0,0), and are colliding all the time.

The way you blit them to screen isn't good, you should use a renderer. Anyway you should probably try some tutorials first, learn what is a Surface and what is a Sprite. Be careful of what you put inside the main loop (why do you create new balls all the time ? they could be created once at startup), your code will be prettier, and your FPS will increase

CGGJE
  • 465
  • 4
  • 7