# C++ Ball Bouncing

This topic is 2131 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello, I am trying to make it so that the balls will bounce off the screen. I have made it so that balls will not go off the screen, but they will not bounce of the edges of the screen. I'll post some code. The code below is where the simple physics are happening. I'm using C++, and SDL2. I can post more code if it is needed. The window size is 800x600.

void Ball::Move()
{
BallRect[0].x += (int)X_Vel[0];
BallRect[0].y += (int)Y_Vel[0];
BallRect[1].x += (int)X_Vel[1];
BallRect[1].y += (int)Y_Vel[1];

if(BallRect[0].x < 0 || BallRect[0].x + BallRect[0].w > 800)
{
BallRect[0].x -= X_Vel[0];
}

if(BallRect[0].y < 0 || BallRect[0].y + BallRect[0].h > 600)
{
BallRect[0].y -= Y_Vel[0];
}

if(BallRect[1].x < 0 || BallRect[1].x + BallRect[1].w > 800)
{
BallRect[1].x -= X_Vel[1];
}

if(BallRect[1].y < 0 || BallRect[1].y + BallRect[1].h > 600)
{
BallRect[1].y -= Y_Vel[1];
}
}


Edited by LeftyGuitar

##### Share on other sites

Well, you also need to reverse the velocity of the balls once they hit the walls so that they move in the opposite direction in the next frame.

if(BallRect[1].x < 0 || BallRect[1].x + BallRect[1].w > 800)
{
BallRect[1].x -= X_Vel[1];
X_Vel[1] *= -1; // This will 'reverse' the direction the ball is going, if you want them to slow down every time they hit a wall you can change the -1 to -0.95 or less
}


And for the other ones too of course.

##### Share on other sites

Thanks, it worked.

• 21
• 11
• 9
• 17
• 13