1

I am writing a pong game with 1 paddle in pygame. The ball is supposed to bounce off the wall and the paddle. But the ball only sometimes bounces off the wall. Here is the code that makes the ball bounce:

    elif ball_x == 785:
        dbx = -dbx
    elif ball_y == 585:
        dby = -dby
    elif ball_y == 15:
        dby = -dby
    elif ball_x == 60 and ball_y > rect1_y - 110 and ball_y < rect1_y + 110:
        dbx = -dbx

How do I fix this?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Varun Rajkumar
  • 374
  • 1
  • 4
  • 13
  • There's not enough code here to really answer this - can you post the rest of it (including the rect1_* variables) ? – match Feb 08 '20 at 20:13

2 Answers2

1

Instead of checking ball_x == 785, instead check ball_x >= 785. As written, your code only makes the ball bounce when its x coordinate is exactly 785. If your ball moves by more than one pixel per frame (which it probably does), then much of the time it will "hop" right over the 785 line and not bounce.

Andrew Merrill
  • 1,672
  • 11
  • 14
1

You have to invert dbx when the ball touches the left or right of the window. And you have to invert dby when the ball touches the top or bottom.
But if the axis aligned component of speed of the ball is n ot exactly 1, then the ball won't touch the border exactly. You have to evaluate if the coordinate is <=, >= rather than ==.

My suggestion is:

radius = 15
width, height = 800, 600

if ball_x <= radius or ball_x >= width-radius:
    dbx = -dbx
if ball_y <= radius or ball_y >= height-radius:
    dby = -dby
Rabbid76
  • 202,892
  • 27
  • 131
  • 174