I am creating an advanced version of the game Pong, where the bats can also move in the x-direction. I am trying to write a code to make the ball bounce off the bats on all four sides of the two bats. I was just able to find codes where the bats are only moveable in y-direction.
It is just an excerpt of the code.
x and y demonstrates the position of the ball, d its diameter.
I do not know why the ball is not reacting to the borders of the bats.
I would be happy if someone could help me! (I am at the beginning of my programming career, so please don’t be too harsh with me)
void reactToBorder () {
//bounce off the left side of bat2
if (x+d/2 == bat2.x && x+d/2 >= bat2.y && x+d/2 <= bat2.y+100) {
dx=dx*-1;
}
//bounce off the right side of bat2
if (x-d/2 == bat2.x+20 && x-d/2 >= bat2.y && x-d/2 <= bat2.y+100) {
dx=dx*-1;
}
//bounce off the bottom of bat2
if (y-d/2 == bat2.y+100 && y-d/2 >= bat2.x && y-d/2 <= bat2.x+20) {
dy=dy*-1;
}
bounce off the top of bat2
if (y+d/2 == bat2.y && y+d/2 >= bat2.x && y+d/2 <= bat2.x+20) { //
dy=dy*-1;
}
//bounce off the right side of bat1
if (x-d/2 == bat1.x && x-d/2 >= bat1.y && x-d/2 <= bat1.y+100) { //bounce off the right side of bat1
dx=dx*-1;
}
if (x+d/2 == bat2.x-20 && x+d/2 >= bat2.y && x+d/2 <= bat2.y+100) {
dx=dx*-1;
}
//bounce off the bottom of bat1
if (y-d/2 == bat1.y+100 && y-d/2 >= bat1.x && y-d/2 <= bat1.x+20) {
dy=dy*-1;
}
bounce off the top of bat1
if (y+d/2 == bat1.y && y+d/2 >= bat1.x && y+d/2 <= bat1.x+20) { //
dy=dy*-1;
}
}