This is unquestionably the dumbest question I’ve asked on this site. I was doing a Pong game a short while ago and spent time getting the ball to bounce away from the paddles in a direction related to where it touched the paddle.
And it seemed to work!
And I failed to comment my code.
And now I’m looking at the code and scratching my head as to how this gibberish does what it’s supposed to do. Can anybody out there parse this for me?
X Axis is the length of the Pong court (the ball travels along this axis during a rally).
Z Axis is the width of the Pong court (the paddles travel this axis in order to return the ball).
The following code is on the ball:
public void BounceBallRelativeToImpact(Vector3 paddlePos, float paddleWidth)
{
float a = transform.position.x - paddlePos.x; // Huh? Local *X* space?
float x = a / paddleWidth; // HUH?? Why even, what does, guh?
int zDir = 0;
if (tf.position.z > paddlePos.z) // Straightforward, which direction should I bounce in.
{
zDir = 1;
}
else
{
zDir = -1;
}
direction = new Vector3(a, 0.0f, zDir).normalized; // ??? => PROFIT
}
This is called via OnCollisionEnter from the paddle that touches the ball, passing in the paddle’s position and the bounds.size.x from the paddle collider.
Sure enough, observation of the game in action suggests that this is doing what it’s supposed to be doing. But:
Why are we getting the ball position in the paddle’s z local space? Why are we dividing this by the paddle’s WIDTH?!?! Is this to do with producing a magnitude that will be normalised later?
God, I’m cursing myself for not commenting this a while ago. It’s fairly simple code, it seems to do the job, I don’t understand it.
MORAL: Kids, comment your code.
Anybody out there feel like helping out a certified idiot? Thank you.
–Rev