Random.Range issue (194283)

Hey guys, so I was following this pong game tutorial and every time someone scores a point the ball resets, waits 1 second, and then flies either left or right.
Here is the code I’m using for that:

  • void GoBall() { float rand =
    Random.Range (0, 2); if (rand < 1)
    { rb2d.AddForce (new Vector2 (20,
    -15)); } else { rb2d.AddForce (new Vector2 (-20, -15)); } }

So it seems as though there are only 2 possible scenarios.. it ends up launching at -20, -15, or 20, -15.. However, sometimes it simply shoots straight down and then just bounces from top to bottom until I hit restart. I’m new to unity, could someone help me understand why this is happening?
thank you so much!!

No, he does not. Yes, he initializes the minRingDistance in a field initializer once at the start but not before the loop. This means it would only work once. Since this code is inside FixedUpdate it's clearly ment to be used more than one time. Actually the variable doesn't need / shouldn't be a member variable in the first place as it's only relevant for the searching process.

1 Answer

1

From your description of the behaviour, that rather sounds like you’re sometimes calling GoBall() twice (once adding (-20,-15), and once adding (20,-15)). I suggest you check the code/event that calls this function.