Objectives

PongGame V9.0

Game of Pong - V9.0

In this lab, you will work on PongGameV9_0.

We will refactor PongGameV8_0 so that it uses the Pythagorean Theorem version for collision detection.

Open your latest version of PongGame version 8. If you wish, you can use this solution here.

Save this as PongGameV9_0.

hitPaddle method

In your PongGameV9_0 class, you will see a hitPaddle method.

Replace it with this code i.e. the pythagoreas version of collision detection:

//method returns true if the ball and paddle overlap (i.e. ball is hit), false otherwise.

boolean hitPaddle(Paddle paddle, Ball ball)
{
   //These variables measure the magnitude of the gap between the paddle and the ball.  
   float circleDistanceX = abs(ball.getXCoord() - paddle.getXCoord() - paddle.getPaddleWidth()/2);
   float circleDistanceY = abs(ball.getYCoord() - paddle.getYCoord() - paddle.getPaddleHeight()/2);

   if (circleDistanceX > (paddle.getPaddleWidth()/2  + ball.getDiameter()/2)) { return false; }
   if (circleDistanceY > (paddle.getPaddleHeight()/2 + ball.getDiameter()/2)) { return false; }

   if (circleDistanceX <= (paddle.getPaddleWidth()/2))  { 
      return true;
   }
   if (circleDistanceY <= (paddle.getPaddleHeight()/2)) { 
      return true;
   } 

   float cornerDistance = pow(circleDistanceX - paddle.getPaddleWidth()/2,  2) +
                          pow(circleDistanceY - paddle.getPaddleHeight()/2, 2);

   if (cornerDistance <= pow(ball.getDiameter()/2, 2)){
      return true;
   } 
   else{
      return false;
   }
}

Run your game to ensure that the collision detection works correctly.

Solution

If your code is not working, the solution can be found here.