Are there better ways to create random behavior?

Hello,

I’m just getting my feet wet with Unity and following some tutorials to get a grasp of the basics. I’m currently coding a “ball” object to start at random. I’ve successfully done so but was wondering if there is a better or more concise code to achieve the same effect or even better randomize the object’s behavior. The current code:

function GoBall () {
	var randomNumber = Random.Range(0, 14);
	if (randomNumber <= 0.5) {
		rigidbody2D.AddForce (new Vector2 (ballSpeed, 10));
	}
	else if (randomNumber <= 1) {
		rigidbody2D.AddForce (new Vector2 (ballSpeed, 60));
	}
	else if (randomNumber <= 2) {
		rigidbody2D.AddForce (new Vector2 (-ballSpeed, -60));
	}
	else if (randomNumber <= 3) {
		rigidbody2D.AddForce (new Vector2 (ballSpeed, 30));
	}
	else if (randomNumber <= 4) {
		rigidbody2D.AddForce (new Vector2 (-ballSpeed, -30));
	}
	else if (randomNumber <= 5) {
		rigidbody2D.AddForce (new Vector2 (ballSpeed, 20));
	}
	else if (randomNumber <= 6) {
		rigidbody2D.AddForce (new Vector2 (-ballSpeed, -20));
	}	
	else if (randomNumber <= 7) {
		rigidbody2D.AddForce (new Vector2 (-ballSpeed, 10));
	}
	else if (randomNumber <= 8) {
		rigidbody2D.AddForce (new Vector2 (-ballSpeed, 60));
	}
	else if (randomNumber <= 9) {
		rigidbody2D.AddForce (new Vector2 (ballSpeed, -60));
	}
	else if (randomNumber <= 10) {
		rigidbody2D.AddForce (new Vector2 (ballSpeed, -30));
	}
	else if (randomNumber <= 11) {
		rigidbody2D.AddForce (new Vector2 (-ballSpeed, 30));
	}
	else if (randomNumber <= 12) {
		rigidbody2D.AddForce (new Vector2 (-ballSpeed, 20));
	}
	else if (randomNumber <= 13) {
		rigidbody2D.AddForce (new Vector2 (ballSpeed, -20));
	}
	else {
		rigidbody2D.AddForce (new Vector2 (-ballSpeed, -10));
	}

Thanks for any help!

If you want a random direction and speed, you can do:

 rigidbody2D.AddForce(Random.InsideUnitCircle * maxSpeed);

If you want a random direction and fixed speed you can do:

rigidbody2D.AddForce(Random.InsideUnitCircle.normalized * ballSpeed);

Note that Random.Range() using integers is exclusive of the final value, so Random.Range(0, 14) produces the values 0 through 13, but not 14. It also only produces integers. This means that your final ‘else’ would never be executed. For what you are doing, use the floating point version:

var randomNumber = Random.Range(0.0, 14.0);

This will produce the full range of values.

If you want these specific values but different/simpler code, you’s either have to 1) find a pattern, 2) put the values in an array, or 3) use some sort of curve to fit the values.