Page 1 of 1

Pong collision detection

Posted: May 21st, 2020, 10:34 pm
by Lividpayment
int BallWidth = xPos + width;
int BallHeight = yPos + height;

if (BallWidth >= PaddleX && xPos <= PaddleX + PaddleWidth &&
BallHeight >= PaddleY && yPos <= PaddleY + PaddleHeight)
{
vx + 1;
BallWidth = PaddleX - 3;
}

if (BallWidth >= PaddleX && xPos <= PaddleX + PaddleWidth &&
BallHeight >= PaddleY && BallHeight <= PaddleY + PaddleHeight)
{
vy - 1;
BallHeight = PaddleY - 3;
}

if (BallWidth >= PaddleX && xPos <= PaddleX + PaddleWidth && yPos <= PaddleY + PaddleHeight && yPos >= PaddleY)
{
vy + 1;
yPos = PaddleY + PaddleHeight + 3;
}



====


Hmmm I can't seem to get the top paddle or the bottom paddle to collide and bounce off correctly. Would someone mind giving me a few pointers in this direction? Thank you!

Re: Pong collision detection

Posted: May 22nd, 2020, 3:26 am
by albinopapa
First off, the names of the variables are a bit confusing and should probably be more descriptively named, though that is hardly the issue I'm sure.

Second,

Code: Select all

if (BallWidth >= PaddleX && xPos <= PaddleX + PaddleWidth &&
BallHeight >= PaddleY && yPos <= PaddleY + PaddleHeight)
and

Code: Select all

if (BallWidth >= PaddleX && xPos <= PaddleX + PaddleWidth &&
BallHeight >= PaddleY && BallHeight <= PaddleY + PaddleHeight)
looks to be the same code and I'm pretty sure this is not the desirable thing you want.

For determining which way to reflect the ball, you should only be testing for one axis at a time:

Code: Select all

if( xPos <= PaddleX + PaddleWidth && BallWidth >= PaddleX ) 
    // adjust the X axis of velocity and position
if( yPos <= PaddleY + PaddleHeight && BallHeight >= PaddleY )
    // adjust the Y axis of velocity and position

Re: Pong collision detection

Posted: May 22nd, 2020, 3:31 am
by albinopapa
As for my comment about names:
BallWidth and BallHeight describes a bounding box around the ball and these represent the width and height of that bounding box, whereas BallRight and BallBottom would tell me the right and bottom side of that bounding box.

Changing the names:

Code: Select all

int BallRight = xPos + width;
int BallBottom = yPos + height;
int PaddleRight = PaddleX + PaddleWidth;
int PaddleBottom = PaddleY + PaddleHeight;

if( xPos <= PaddleRight && BallRight >= PaddleX )
    // adjust the X axis of velocity and position
if( yPos <= PaddleBottom && BallBottom >= PaddleY )
    // adjust the Y axis of velocity and position