Pong Collision Detection

Started by
5 comments, last by Sickilla 22 years, 9 months ago
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
X4J
Advertisement
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.


nope, tried that already, i tried just about everything

X4J
X4J
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.
i think midnight is right..
"All programmers are playwrights and all computers are lousy actors." -Anon.
thanx alot man, i cant believe i let that slip by me. sometimes i can be real stupid. sorry for wasting your time.

X4J
X4J
No, not your fault. it''s always the small things like that that get by. The best thing to do is just play the code out in your head and make sure it all makes sense.

This topic is closed to new replies.

Advertisement