Pregunta

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.

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top