Reputation: 189
I am trying to make this Vector2 have the first value either be equal to -7 or 7. The second value to be -5, 5 or anything in between. I can not seem to figure out how to make the first value either -7 or 7 and nothing in between. Please help
rb2d.velocity = new Vector2(Random(-7,7) , Random.Range(-5,5));
Upvotes: 1
Views: 1933
Reputation: 11
This is a solution to your question:
Random random = new Random();
// Get a value between -5 and 5.
// Random.Next()'s first argument is the inclusive minimum value,
// second argument is the EXCLUSIVE maximum value of the desired range.
int y = random.Next(-5, 6);
// Get value of either 7 or -7
int[] array = new int[] { 7, -7 };
int x = array[random.Next(array.Length)]; // Returns either the 0th or the 1st value of the array.
rb2d.velocity = new Vector2(x, y);
It is important to know that the random.Next(-5, 6); returns a value between -5 and 5. Not -5 and 6, as it seems at first sight. (Check the function's description.)
Upvotes: 0
Reputation: 271355
You can use Next
to generate randomly either a -1 or 1 like this:
Random r = new Random();
int randomSign = r.Next(2) * 2 - 1;
To make that a 7 or -7, you just multiply by 7:
rb2d.velocity = new Vector2(randomSign * 7 , Random.Range(-5,5));
Because this seems like Unity, here is how to do it with the Unity Random.Range
method:
int randomSign = Random.Range(0, 1) * 2 - 1;
Upvotes: 4
Reputation: 1935
It should be something like this:
int[] numbers = new int[] { -7, 7 };
var random = new Random();
vrb2d.velocity = new Vector2(numbers [random.Next(2)] , Random.Range(-5,5));
Put all numbers in a vector and pick randomly the index. Easy enough.
Upvotes: 2