Why does my Pong ball collision code sometimes not work

I'm creating a pong game with C++ for a University project. I have this snippet of code that check to see if my ball sprite has hit the boundary of my screen. When it does, it will multiply my ball_direction.y value (for a vector) by -1 to produce a bounce. However, most of the time this works, but sometimes the ball will simply go through and off the screen without bouncing, and sometimes it will get stuck on the edge and bounce back and forth before flying off the screen again.

I'm really not sure why this works, and I haven't found a solution. If you need to see other areas of my code, please ask, I'm still pretty new to this.

1
2
3
4
  if (ball->yPos() + ball->height() > game_height || ball->yPos() < 0)
    {
      ball_direction.y *= -1;
    }
1. Why is ball_direction a different object to ball ?
It's motion is just as much a part of the ball object as it's position and size.

2. Also, having found the ball is outside the box, you need to put the ball back in the box at the same time you reverse the direction.

Otherwise, if on the very next update of the position, it's still outside the box, you end up with a double reversal and flying off into space.
Topic archived. No new replies allowed.