Hello!

I've finished the pong tutorial from the official documentation over the weekend and it was a good exercise! I got the game working and all, but there was one thing I didn't quite understand, and it's how the direction.y is being calculated. Here is the code from the tutorial:

# Flip, change direction and increase speed when touching pads
if ((left_rect.has_point(ball_pos) and direction.x < 0) or (right_rect.has_point(ball_pos) and direction.x > 0)):
    direction.x = -direction.x
    direction.y = randf()*2.0 - 1
    direction = direction.normalized()
    ball_speed *= 1.1

I'm assuming randf() generates a random float number between 0 and 1, but why is there the *2.0-1 part? And how is the result of that being translated into a direction? Shouldn't it be a number between 1-360, representing angle degrees?

[EDIT] I didn't read the question properly, please skip to next comment as this one is garbage!!

Godot uses radians internally, I believe. So randf()*2.0 - 1 will generate a float value between -1 and 1, which i think in radians would be roughly between -57 and 57 degrees.

you could see what angle is generated by calling a print(rad2deg(direction.y)) each time it is calculated.

Sorry, I realised I typed a load of nonsense above. I hadn't read the question properly or looked at the tutorial. randf()*2 -1 does indeed return a float between -1 and 1 but this is the vertical speed of the vector and nothing to do with radians at all.

This picture may explain it better:

so if direction.y = 1 then you would have a 45 degree angle from the horizontal for example (as direction.x =1 or -1)

this image may help clarify:

direction.normalized() adjusts the size of that (randomly generated) direction speed to = 1 so that the speed is kept consistent regardless of the angle generated.

This is an example of how this is achieved:

Sincere apologies if I added to the confusion, I should've read the question more thoroughly (lesson learnt for me!). Vector math is quite useful in games development and there are many tutorials out there that are worth checking out, like this one

Hope that clears things up.

Hey Chris! Thanks for coming back! Yeah this was a lot more clarifying! specially after reading Godot's documentation on vector math as well, which allowed me to understand better the direction.normalized() and unit vectors!

6 years later