- Home /
Random.Range issue
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!!
Answer by tanoshimi · Aug 26, 2017 at 06:55 PM
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.
So I tried looking through my code but I can't seem to find anything..
The first code below is the simple function that resets the ball to the middle of the screen and calls the GoBall function.
void RestartGame() {
ResetBall ();
Invoke ("GoBall", 1);
}
---- This code down here is what causes the ball to be reset after it touches either the left or right wall. I think the problem that you're talking about would probably exist within this function but I can't seem to find it. Do you see any issues?
void OnTriggerEnter2D (Collider2D hitInfo) {
if (hitInfo.name == "Ball") {
string wallName = transform.name;
Game$$anonymous$$anager.Score (wallName);
hitInfo.gameObject.Send$$anonymous$$essage ("RestartGame", 1.0f, Send$$anonymous$$essageOptions.RequireReceiver);
}
}
Thanks so much for the response!
Try adding a Debug.Log to that function that prints out each time the ball is reset.