I'm trying to make a pong clone and am having trouble grasping ball deflection. The way I'm approaching it is to increase the angle by how far the ball collides from the middle of the paddle. However, I can't seem to get the math right and I've tried so many things that I'm beginning to doubt what I know.

The issue I'm running into is that I can get the angle I want in degrees, but I can't figure out the correct way to apply it to the velocity vector. Is there a way that I can take ANY angle and apply it evenly across the ball velocity?

For example, when the game starts I set the velocity to -5,5 so that it heads left. If I were to calculate the angle of deflection as 50 degrees, what operation am I looking at to apply that to the velocity? Converting degrees to radians won't work because that would create fractional numbers and my velocity and position are ints. I've considered just hardcoding ranges of distance from paddleY into different velocities, but I was hoping there might be a better way.

  • 1
    \$\begingroup\$ Velocities at arbitrary angles already require fractions. If you stick to integers, there are only twelve velocities that maintain the same speed: (±5,±5) or (±7,±1) or (±1,±7). A 50° rotation from (-5, 5) takes you to (0.61628..., 7.04416...) — not an integer coordinate. I'd recommend that you store your position and velocity using float or fixed point, and round to integers for display only. \$\endgroup\$ – DMGregory Feb 13 '20 at 15:23
  • \$\begingroup\$ That's a fair recommendation. I didn't consider the actual number of velocities that would be available. I do think keeping more precise position and velocity on top of the int values that are used for rendering is a better solution. I hate that I got so focused on what I was trying to solve that I didn't come up with it myself. Thanks! \$\endgroup\$ – Eric Feb 13 '20 at 17:01
  • 1
    \$\begingroup\$ You might want to refresh your memory of rotation matrices. The operation you've described is a non-uniform scale, not a rotation. In order to do a rotation, there needs to be some way for my input x to creep into the output y and vice versa, otherwise we'd never be able to rotate from (1, 0) to (0, 1) and back. \$\endgroup\$ – DMGregory Feb 13 '20 at 21:50
  • 1
    \$\begingroup\$ Thanks again for the input, I got it to work! This is obviously way overkill for a pong implementation versus just breaking the paddle into chunks and applying arbitrary angles based on where it hits. But it was something I wanted to learn to do because I couldn't wrap my head around it. \$\endgroup\$ – Eric Feb 14 '20 at 2:49
  • 1
    \$\begingroup\$ Great! Want to write up your solution as an Answer below? \$\endgroup\$ – DMGregory Feb 14 '20 at 2:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.