Back

Technologies:

javascriptjavascript
avatar
Tolerim
a day ago

What is the process for causing a ball to bounce away from a paddle at a certain angle based on where it makes contact?

I'd like to implement a feature where the ball bounces off at a specific angle based on the paddle's location. For example, if the ball hits the top of the paddle, it should bounce upwards. Although I tried using the below code, the ball just flips around and continues moving in the same direction.

if (ballx < 15 && bally < paddle1 + paddle1height / 2 && bally > paddle1 - paddle1height / 2) {
        angle += 180;
    }
    if (ballx > 585 && bally < paddle2 + paddle2height / 2 && bally > paddle2 - paddle2height / 2) {
        angle += 180;
        }
Is there a way to achieve this behavior? If so, please provide your suggestions. Thank you!

Answers(1)
avatar
Tolerim
a day ago
Verified Answer
To make the ball bounce off at an angle depending on where it hits the paddle, you need to calculate the angle of reflection and then use that to update the angle of the ball. Here's an example of how you can do this:
if (ballx < 15 && bally < paddle1 + paddle1height / 2 && bally > paddle1 - paddle1height / 2) {
  // Ball hit paddle 1
  let paddleHitPosition = (bally - (paddle1 - paddle1height / 2)) / paddle1height;
  let angleRad = (Math.PI / 4) * (2 * paddleHitPosition - 1);
  angle = (angleRad * 180) / Math.PI;
}

if (ballx > 585 && bally < paddle2 + paddle2height / 2 && bally > paddle2 - paddle2height / 2) {
  // Ball hit paddle 2
  let paddleHitPosition = (bally - (paddle2 - paddle2height / 2)) / paddle2height;
  let angleRad = (Math.PI / 4) * (2 * paddleHitPosition - 1);
  angle = 180 - ((angleRad * 180) / Math.PI);
}
In this example, we first calculate the position of the ball relative to the paddle by dividing the distance between the ball's y-coordinate and the top of the paddle by the height of the paddle. This gives us a value between 0 and 1 that represents where the ball hit the paddle. We then use this value to calculate the angle of reflection using the formula angle = (Math.PI / 4) * (2 * paddleHitPosition - 1). Finally, we convert the angle from radians to degrees and update the angle variable. If the ball hits paddle 1, we use the calculated angle directly, but if it hits paddle 2, we need to flip the angle horizontally before updating it.
;