Archived

This topic is now archived and is closed to further replies.

Pong Collision Detection

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Why doesn''t this collision detection code work? // test of the ball has hit player 2''s paddle if (ball_y < (SCREEN_HEIGHT/2) && ball_dy > 0) { // extract leading edge of ball int x = ball_x-2; int y = ball_y-2; // test for collision with paddle2 if ((x >= P2paddle_x && x <= P2paddle_x+P2PADDLE_WIDTH) && (y >= P2paddle_y && y <= P2paddle_y+P2PADDLE_HEIGHT)) { // reflect ball ball_dy=+ball_dy; // push ball out of paddle since it made contact ball_y+=ball_dy; // add a little randomness to the ball if (KEY_DOWN(VK_RIGHT)) ball_dx-=(rand()%3); else if (KEY_DOWN(VK_LEFT)) ball_dx+=(rand()%3); else ball_dx+=(-1+rand()%3); P2score+=100; // make a little noise MessageBeep(MB_OK); // return return; } // end if } // end if the problem seems to come at the following bit of code if ((x >= P2paddle_x && x <= P2paddle_x+P2PADDLE_WIDTH) && (y >= P2paddle_y && y <= P2paddle_y+P2PADDLE_HEIGHT)) i have tried modifying it multiple times but it still don''t work but the player1''s paddle detection is similar but works great. X4J

Share this post


Link to post
Share on other sites
I dunno if this is it but try this:

Instead of doing this:
// reflect ball
ball_dy=+ball_dy;

Do this:
// reflect ball
ball_dy=-ball_dy;

Hope that works.


Share this post


Link to post
Share on other sites
Wait a minute, your first line of code (aside from the comment) checks to see if the ball is located in the top half of the screen. This is fine if your second paddle is on the top half of the screen (if not, change the less than to a greater than). But more importantly, the line also checks whether the velocity of the ball is greater than 0. That would mean a positive velocity, which would mean the ball would be moving down (unless you are using a different coordinate system). So, if the paddle is located at the top of the screen, then why test collision when the ball is moving down? If this is your problem, you should be checking to see if ball_dy < 0.

Share this post


Link to post
Share on other sites