Advertisement

Pong!

Started by May 16, 2001 05:26 PM
1 comment, last by BlackHwk4 23 years, 6 months ago
I'm making a 2D pong game and can make the ball (it's actually a square) bounce off the walls but can't figure out how to make it bounce off one of the paddles. Here's what the paddle and ball look like:

        // Paddle
	glNewList(paddle,GL_COMPILE);
		glBegin(GL_QUADS);
			// Top right
			glVertex2f(0.069f,0.5f);
			// Top left
			glVertex2f(-0.069f,0.5f);
			// Bottom left
			glVertex2f(-0.069f,-0.5f);
			// Bottom right
			glVertex2f(0.069f,-0.5f);
		glEnd();
	glEndList();

	// Ball
	glNewList(ball,GL_COMPILE);
		glBegin(GL_QUADS);
			// Top right
			glVertex2f(0.095f,0.095f);
			// Top left
			glVertex2f(-0.095f,0.095f);
			// Bottom left
			glVertex2f(-0.095f,-0.095f);
			// Bottom right
			glVertex2f(0.095f,-0.095f);
		glEnd();
	glEndList();
 
I don't know if that will help someone give me an answer to my question. I was thinking maybe that if I could some how test the top right and bottom right the paddle (assuming it's on the left) to see if it got hit by the top left and bottom left of the ball but I'm not really sure how to do that. Thanks for any help. Edited by - BlackHwk4 on May 16, 2001 6:27:34 PM
First find the center point of the ball...this code assumes you know the width (BALL_SIZE) of your ball and that you are using the upper left corner of the ball as your x,y coord...

ball_cx = ball_x + (BALL_SIZE/2);
ball_cy = ball_y + (BALL_SIZE/2);

Now check to see if the ball hit the paddle...This also assumes that the paddles x,y coord is the top left and you know the width and height of your paddle....

if ((ball_cx >= paddle_x && ball_cx <= paddle_x + PADDLE_WIDTH) && (ball_cy >= paddle_y && ball_cy <= paddle_y + PADDLE_HEIGHT))
{

If you make it into this if statement the ball has collided with the paddle. You need to reflect it off the paddle now by reversing its velocity and adding the reversed velocity to its position...

//reflect the ball
ball_dy = (-ball_dy);

//Push the ball away
ball_y += ball_dy;
}

A pretty simple solution but it works just fine, especially for pong. Hope this helps.

Mike Barela
MikeB@yaya.com
Mike BarelaMikeB@yaya.com
Advertisement
Thanks it worked!

This topic is closed to new replies.

Advertisement