# Unity Change Ball Direction after hitting paddle in a Pong game (like in dx-ball)

I'm struggling with how to get the ball to change the bounce based on where it hits on the paddle. Normally in a pong game, the angle changes, depending on how far from center the ball bounces, and which direction of the center it bounces. I managed to do something like that:

//rb = rigidbody, velOnPaddleHit = predefined float
float dist = transform.position.x - paddle.position.x;
dist = transform.position.x > paddle.position.x ? dist : -dist;
dist /= paddle.localScale.x/2;
dist *= velOnPaddleHit;
rb.addForce(dist, 0,0);


But it's just not working / it's weird. Can anyone help me?

Edit: Here's the video showing this kind of behaviour. When the ball hits the left side of the paddle, it goes left, the velocity doesn't matter

https://www.youtube.com/watch?v=fHX_2DLDp1w

• Apparently there is a mistake in your code. You supplied "-dist" explicitly, as dist in not an abs value, it will retain its + or - sign, so no need to provide -dist, otherwise -(-dist) will become +dist. Just use dist only – Hamza Hasan Mar 5 '16 at 21:37
• Did you read the post? I'm checking whether the ball is on the right or on the left side of the paddle. – Mateusz Sowiński Mar 6 '16 at 0:03
• What are you doing after finding that? Modifying dist variable by +ve or -ve, which you are not suppose to do – Hamza Hasan Mar 6 '16 at 0:16

## 1 Answer

Calculate the dot product of the ball's position, relative to the center of the paddle, and a fixed reference direction:

Both vectors must be normalized. While bouncing, invert the y-component of the ball's velocity and use the dot product to adjust the x-component.

• Sorry, im an amateur, i couldn't understand a word you said :( but it seems that youre trying to tell me how to calculate the distance from the canter of the paddle to the ball, but i've done that (transform.position.x - paddle.position.x). I just need the distance on the x axis – Mateusz Sowiński Mar 5 '16 at 18:35
• @MateuszSowiński, this uses the same vector, but not the length. This compares the ball<>paddle angle (cyan) to the paddle's "right" (red). This calculation will produce -1 on the left edge of the paddle, 0 in the middle, and +1 on the right edge. You can scale that by some factor and then add it directly to velocity.x. – Jon Mar 5 '16 at 22:55
• Yes i'm aware of that but what i'm trying to do is actually change the x velocity but leave the magnitude so i would need to decrease the y velocity. I'm still figuring how to do that using phitagorean therom, and i think im close – Mateusz Sowiński Mar 6 '16 at 0:07
• @MateuszSowiński, you can normalize the modified velocity vector, making its' magnitude 1.0f. Then, multiply that unit-vector by the desired magnitude. – Jon Mar 6 '16 at 3:15