View more

View more

View more

Image of the Day Submit

IOTD | Top Screenshots

The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

C++ Ball Bouncing

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

2 replies to this topic

#1LeftyGuitar  Members

Posted 14 September 2013 - 03:57 PM

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, 14 September 2013 - 03:58 PM.

#2Horscht  Members

Posted 14 September 2013 - 04:15 PM

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.

#3LeftyGuitar  Members

Posted 14 September 2013 - 04:50 PM

Thanks, it worked.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.