Creating a full game for the first time no doubt brings about surprises. But one surprise I didn’t expect was having to dig up the little high school trigonometry knowledge I’d long ago buried in the deep recesses of my brain. So dust off the cobwebs and come along for the ride. Here’s your daily dose of vector math.
Aim Assist Ball
In the process of designing ball powerups for our game, we decided to add an aim assist ball that would show players the trajectory of the ball, as well as the first deflection, allowing players to line up their shots more accurately for long shots. The task of programming this nifty little powerup fell to me.
Ball Physics
To start, I looked at the ball physics of classics like Pong and Arkanoid, analyzing the angles of deflection and trying to figure out the patterns. Soon, it was time to get out the graph paper and start plotting points.
In order to show the trajectory, I would need to know the initial angle the ball was aimed. In order to figure out the angle of deflection, I would need to figure out the orientation of the surface the ball would hit, as well as the angle of the collision.
After plugging and chugging several sets of numbers and angles, I finally realized the common thread. So for those of you still hoping to create a Pong game of your own, here’s the anatomy of ball deflection.
Hit Normal
First and foremost, we need to figure out the orientation of the surface the ball hits. Is the surface vertical, horizontal, or diagonal? Luckily, the hit.normal provides this information. The normal of the hit point provides the direction that’s perpendicular to the surface that was hit.
Deflection Point
To figure out the point of deflection, just reflect your initial point (the ball origin) over the normal. Double the distance between the normal and your origin, and plop down your deflection point.
For vertical surfaces, the x-coordinate of the deflection and origin will be the same, while the y-coordinate will change, and vice versa for horizontal surfaces.
Diagonal Surfaces
This is all fine and dandy for horizontal and vertical surfaces, but things start getting tricky with diagonal surfaces. Fortunately, we can turn to the dot product of points A and B. The dot product gives us the distance between the hit point and the midpoint of line segment AB. Double this to figure out the distance between A and B, then reflect over the normal as before. Simple, right?
Here’s a sneak peak of the aim assist ball in action: