3

My code seems to work some of the time but the majority of the time the ball seems to just do what it wants. I assigned an angle to the ball class that changes up impact with the top and bottom of the screen as well as the player paddles, but sometimes the ball seems to ignore the logic and 'if' statements. I'm sure that I'm just missing something simple, but any help would be appreciated.

Note: "T_RECT" and "B_RECT" stand for the top and bottom of the screen respectively.

 if (gameBall.rect.colliderect(T_RECT) or gameBall.rect.colliderect(B_RECT)) and bounce == 0:
        gameBall.angle = 545 - gameBall.angle
        bounce = 1
    if (gameBall.rect.colliderect(redPlayer.rect) or gameBall.rect.colliderect(bluePlayer.rect)) and bounce == 0:
        gameBall.angle =  365 - gameBall.angle
    else: bounce = 0
tshepang
  • 12,111
  • 21
  • 91
  • 136
  • 1
    What exactly are the symptoms when the logic and if statements are ignored? – ouflak Jun 20 '14 at 23:17
  • What I suspect, from looking at your code, is that you are assuming that every condition in your conditional is being checked, and then on that basis there is decision on whether to proceed through into the statements or not. But this is almost certainly not the case with most compilers. They will optimize those conditional checks, and as soon as **even just one truth condition is met**, the code will proceed without checking anything else in the conditional. – ouflak Jun 20 '14 at 23:22
  • 1
    What exactly doesn't work? What happens? What should happen instead? – pts Jun 20 '14 at 23:27
  • Is it possible that the velocity of your ball collided deep enough into the rect that it is still in a collided state after the bounce? This might cause it to remain in a bounce loop where the ball essentially is stuck on the rect. Or maybe just a similar edge case like that. – woot Jun 21 '14 at 00:18
  • In other words, to expand woot's explanation, you should check independently if it hits the T_RECT or the B_RECT. In the first case you should change the angle only if it is currently "going up"; in the second case only if it is currently "going down". – Armin Rigo Jun 21 '14 at 07:37

1 Answers1

0

When doing these type of ball/bouncing collisions I was having a lot of trouble.

The simplest solution I found is to:

-Move ball on X-axis

-check for collision, if a collision happened, fix it and react to it (in most cases reverse x direction)

-Do the same on the Y-axis.

I used to pull my hair out over this. Now I update/collide-check the axes individually. Works great.