shak.s
shak.s

Reputation: 429

pong ball won't reflect off bottom an top of canvas

   function ballReset(){
    ballSpeedX=-ballSpeedX;
    ballX = canvas.width/2;
    ballY = canvas.height/2;
}

function moveEverything(){
    ballX = ballX+ ballSpeedX;
    ballY = ballY+ ballSpeedY;
    if (ballX<0 ){
        if(ballY > paddle1Y&&
            ballY < paddle1Y+PADDLE_HEIGHT){
ballSpeedX = -ballSpeedX;

        }else{
        ballReset();
    }}

    if (ballX>canvas.width ){
        if(ballY>paddle1Y&&ballY<paddle2Y+PADDLE_HEIGHT){
            ballSpeedX = -ballSpeedX;
        }else{
            ballReset()};

    if (ballY<0 ){
        ballSpeedY=-ballSpeedY;
    }
    if (ballY>canvas.height ){
        ballSpeedY=-ballSpeedY;
    }}}

the ball won't reflect off the bottom and top of the canvas. I'm not sure what's wrong in my code, can someone tell me what's wrong?

Upvotes: 0

Views: 34

Answers (1)

shiftweave
shiftweave

Reputation: 178

Your upper and lower boundary checks are nested inside your right edge boundary check. This means that your ball can only bounce off the top or bottom if it simultaneously bounces off the right edge. Proper indentation shows this very clearly:

if (ballX > canvas.width) {
    if (ballY > paddle1Y && ballY < paddle2Y + PADDLE_HEIGHT) {
        ballSpeedX = -ballSpeedX;
    } else {
        ballReset()
    }

    if (ballY < 0) {
        ballSpeedY = -ballSpeedY;
    }
    if (ballY > canvas.height) {
        ballSpeedY = -ballSpeedY;
    }
}

Moving the upper and lower boundary checks outside the right boundary check should improve the situation. The takeaway here is that while indentation and line breaks don't technically have any functionality, they are still important. If you're unsure how to accomplish this, pick a style guide and stick to it - consistency is king. Typically closing braces should be on their own line, and opening braces mean that the entire contents between the two braces should be indented a little bit more.

"K&R style" is very common and sums up the brace game. https://en.wikipedia.org/wiki/Indentation_style#K&R

Upvotes: 1

Related Questions