0
votes

Hi I'm trying to make a simple pong game and I'm running into trouble with the collision detection. The ball is not registering with the paddle.

    function moveBall() {
    var rightRadius = ballX + radius;
    var leftRadius = ballX -radius;

    if (ballX + radius > canvas.width || ballX - radius < 0) {
        ballOffX = -ballOffX;
    }
    /*
    The following code is handling the collision of the ball with the plate
     */
   if((rightRadius <= (player1.x + paddleWidth))&&(leftRadius >= player1.x) &&(player1.y == ballY + 10)){
        ballOffY = -ballOffY;
    }

    ballX += ballOffX;
    ballY += ballOffY;

}

enter image description here

1
player ball plate ? can you show a example image ? - Madhawa Priyashantha
I renamed the plate to paddle hopefully that helps. Thanks - Muffin
you should use vector to detect collision. - kollein
player1.y == ballY + 10 is your problem. You probably want an inequality, otherwise you're assuming that the ball will at some point be located at exactly that y position, which is unlikely given a dynamic velocity. - Patrick Roberts

1 Answers

0
votes

I made an if statement to sense collisions in JavaScript, here it is:

if circle x < rect x + circle width && circle x + rect width > rect x && circle y < rect y + circle height && rect height + circle y > rect y {

this works by putting the ball inside of an 'imaginary box' and when any of the edges of the 'imaginary box' touch any of the edges of the rectangle, the collision is detected.