How to make a ball bounce off a paddle at a certain angle depending on where it hit the paddle?

1.3k views Asked by At

So I have two separate detections for collision for both the player paddle and the enemy paddle and in the player paddle I have commented out what seems to be the math calculation needed to bounce a ball based on where it hit. The code that isn't commented simply bounces the ball around the screen as you would expect when you reverse the velocity (it's velocity is a float value) on each bounce. So for starters, is the commented out formula actually the correct formula, and if so does it need to be applied to both xSpeed and ySpeed when it collides with a paddle?

When I saw this formula it took BallAngle or PaddleAngle as an argument (I can't remember to be honest). Now if this IS the correct formula, how do I even get that angle in the first place? I'm just using integer's in there (for testing) because I don't know how to get the angle.

if (ball.getPosition().x < (player.getPosition().x) //PLAYER COLLISION DETECTION
&& (ball.getPosition().y + (ball.getRadius() * 2)) >= player.getPosition().y
&& ball.getPosition().y <= (player.getPosition().y + player.getSize().y))
{
    xSpeed = -xSpeed;
    //xSpeed = xSpeed*cos(91);
    //ySpeed = ySpeed*sin(90);
    ball.move(xSpeed, ySpeed);              
}

if (ball.getPosition().x > enemy.getPosition().x - 30 //ENEMY COLLISION DETECTION
&& (ball.getPosition().y + (ball.getRadius() * 2)) >= enemy.getPosition().y
&& ball.getPosition().y <= (enemy.getPosition().y + enemy.getSize().y))
{
    xSpeed = -xSpeed;
    ball.move(xSpeed, ySpeed);
}
1

There are 1 answers

1
sjdowling On

cos(91) is just under -1, presumably it is meant to reverse the X direction and slow it down due to the impact. sin(90) is almost one so again is presumably meant to slow it down a bit.

Of course these functions are actually quite expensive to calculate so you may as well just hard code the values.

const float xBounce = -0.99436746092
const float yBounce = 0.8939966636  
...
xSpeed *= xBounce;
ySpeed *= yBounce;
ball.move(xSpeed, ySpeed);