Sign in to follow this  
LeftyGuitar

C++ Ball Bouncing

Recommended Posts

LeftyGuitar    245

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 this post


Link to post
Share on other sites
Horscht    270

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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this