Search code examples
javascriptcanvaspong

Can't achieve to beat a ball in my JS Pong Game


I've written a simple pong game in JS,but i can't force ball to change it direction while it touches a paddle.Below i've inserted my actual beatControl funtcion.

function beatControl() {

if (ballX + ballSize >= xAiPosition) {
    ballSpeedX = -ballSpeedX;
    //console.log(ballX);
} else if (ballX == xPosition + paddleWidth) {
    ballSpeedX = -ballSpeedX;
    // console.log(ballX);
}

}

Here's the link to my game


Solution

  • Here is an example collision I have used in a JS pong game that I made. First it checks if it is far enough to the right or to the left, and if that is true then it checks if the paddle is also within the proper Y value to hit the ball. You can review my source code here - http://pongio.bitballoon.com/

        //Ball hits left paddle
        if (ball.x<=paddleLeft.width+ball.r && ball.y>=paddleLeft.y && ball.y<=paddleLeft.y+paddleLeft.height) {
            ball.velX = -ball.velX;
        }
        //Ball hits right paddle
        else if (ball.x>=canvas.width-(paddleLeft.width+ball.r) && ball.y>=paddleRight.y && ball.y<=paddleRight.y+paddleRight.height) {
            ball.velX = -ball.velX;
        }