Nick Solonko Nick Solonko - 1 month ago 11
Javascript Question

Why does the ball in my game not stop at the border and bounce back?

I am making a simple pong game and I want the ball to just bounce around the HTML5 canvas, but stay in bounds. It bounces correctly from the right and bottom borders, but goes inside the top and left borders a little bit.

Code:

if(ballY<=0){
ballSpeedY = -ballSpeedY;
}

else if(ballY>=HEIGHT-10){
ballSpeedY = -ballSpeedY;
}




if(ballX >= WIDTH-10){

ballSpeedX = -ballSpeedX;

}


else if(ballX <= 0){

ballSpeedX = -ballSpeedX;

}


Here I change the ball's velocity if it is near the borders. To make it work correctly, I have to change the number in the if statements to 8 instead of 0. Why is that? Here is the JFiddle. I can just fix the issue with changing the 0 to 8, but I want to know why this happens.

Answer

It happens on all 4 sides of your canvas, however on the right and bottom you have ballX >= WIDTH-10 and ballY >= HEIGHT-10 respectively.

You need to make the same to the other sides as well, like ballY <= 10 for top and ballX <= 10 for left.

This happens for one simple reason - your ball coordinates counted from its' centre. That is the 0, 0 of your ball, like the 0, 0 of your rectangle is the top left corner.

And when you say ballX <= 0 it means the ball will have to touch the boundary with its center point and for that it has to go inside your left border.