0

I have been working on a basic Pong clone using processing.js. Currently I have a ball which can be bounced back and forth between two player controlled paddles. My issue is that my algorithm for detecting collision between the balls and the paddles reverses the ball but leaves an unrealistic gap for the rightmost paddle. The method I am using for collision detection is as follows:

    /*
     * Collision detection
     */
     void Collide(PongBall ball, Paddle pPaddle)
     {

        float paddleX = pPaddle.x;

        if(ball.directionX == -1)
        {
            //moving backwards
            float paddleFront = pPaddle.x + pPaddle.width + ball.mass/2; 
            float paddleBack = pPaddle.x;


            if( (ball.x <= paddleFront && ball.x >= paddleBack)
               && (ball.y >= pPaddle.y - pPaddle.height - ball.mass)
               && (ball.y <= pPaddle.y + pPaddle.height + ball.mass))
            {
                //contact with paddle
                debugger;
                ball.velocity.x *= -1;
                ball.directionX *= -1;
            }  
        }
        else if(ball.directionX == 1)
        {
            //moving forwards
            float paddleFront = pPaddle.x - pPaddle.width - ball.mass/2; 
            float paddleBack = pPaddle.x;


            if( (ball.x >= paddleFront && ball.x <= paddleBack)
               && (ball.y >= pPaddle.y - pPaddle.height - ball.mass)
               && (ball.y <= pPaddle.y +pPaddle.height + ball.mass))
            {
                debugger;
                ball.velocity.x *= -1;
                ball.directionX *= -1;
            }  
        }
     }

The code/example in its entirety is located on jsfiddle here.

I can adjust the value for calculating the paddleBack value for the rightmost paddle by removing the ball.mass/2 and so on to assuage the value so that the collision looks better, but I would like to understand, why does calculation for the collision on the left side differ from that on the right? Thank you in advance.

Christian
  • 1,685
  • 9
  • 28
  • 48

1 Answers1

0

I had a hunch

        //moving forwards
        float paddleFront = pPaddle.x - pPaddle.width + ball.mass/2; 
        float paddleBack = pPaddle.x;

the + ball.mass/2 instead of - ball.mass/2 made the difference

Ozzy
  • 8,244
  • 7
  • 55
  • 95
  • Thank you, that did correct the issue. I think I was mistakenly assuming that the x for a rectangle would always be innermost when it is actually the leftmost side. – Christian Mar 20 '13 at 18:48
  • And thank you for introducing me to processing.js. Going to have a lot of fun with this :) – Ozzy Mar 20 '13 at 18:54