I've been working on making Pong in OpenGL and SDL and currently have both paddles and the game ball set up properly. I have an Object (or Entity) class which is used to instantiate each of the entities in the game. The Object class constructor takes a width and a height for the object, the direction in which it moves (x and y), its position, its speed, and rotation.
In order to detect whether the ball has collided with either a paddle or the top or bottom of the screen, I do the following checks:
// Collision with the top
if ((ballTop >= topWallBottom) || (ballBottom <= bottomWallTop)) {
ball.yDir = -ball.yDir;
}
// Collisions Left Paddle - Ball
if ((
(leftPaddleBottom > ballTop) ||
(leftPaddleTop < ballBottom) ||
(leftPaddleLeft > ballRight) ||
(leftPaddleRight < ballLeft))) {
}
else{
ball.xDir = -ball.xDir;
ball.yDir = -ball.yDir;
}
if ((
(rightPaddleBottom < ballTop) ||
(rightPaddleTop > ballBottom) ||
(rightPaddleLeft > ballRight) ||
(rightPaddleRight < ballLeft))) {
}
else{
ball.xDir = -ball.xDir;
ball.yDir = -ball.yDir;
}
The dimensions of each object are defined by essentially using the width and height of each object, dividing either value by two (for either the x or the y direction) and checking if the ball's (collision box) position has intersected with that of a paddle or a border:
// Ball dimensions
float ballTop, ballBottom, ballLeft, ballRight;
ballTop = ball.posY + (ball.height / 2.0f);
ballBottom = ball.posY - (ball.height / 2.0f);
ballLeft = ball.posX - (ball.width / 2.0f);
ballRight = ball.posX + (ball.width / 2.0f);
// Wall Dimension
float topWallBottom = topWall.posY - (topWall.height / 2.0);
float topWallTop = topWall.posY + (topWall.height / 2.0);
float bottomWallBottom = bottomWall.posY - (bottomWall.height / 2.0);
float bottomWallTop = bottomWall.posY + (bottomWall.height / 2.0);
// Left Paddle Dimensions
float leftPaddleTop = leftPaddle.posY + (leftPaddle.height / 2.0f);
float leftPaddleBottom = leftPaddle.posY - (leftPaddle.height / 2.0f);
float leftPaddleRight = leftPaddle.posX + (leftPaddle.width / 2.0f);
float leftPaddleLeft = leftPaddle.posX - (leftPaddle.width / 2.0f);
// Right Paddle Dimensions
float rightPaddleTop = rightPaddle.posY + (rightPaddle.height / 2.0f);
float rightPaddleBottom = rightPaddle.posY - (rightPaddle.height / 2.0f);
float rightPaddleRight = rightPaddle.posX + (rightPaddle.width / 2.0f);
float rightPaddleLeft = rightPaddle.posX - (rightPaddle.width / 2.0f);
For some reason, the ball seems to be passing right through the paddle and not redirecting at all. I'm pretty sure that I have everything set up correctly but I can't really determine what is preventing the ball's collisions from being detected.
Is there something that I'm doing wrong conceptually, or is there just a small mechanical issue? I feel like its the latter, but I can't be sure.
Here is the full code for reference.
Of course, any other specific suggestions about how to implement collision detection here would be welcomed, thanks!