Instantiate objects in given range
I am trying to Instantiate objects on the right and the left side of the player but not in front of it. ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ So let's assume the player's transform.position.x value is "0".⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ I want to Instantiate the object between X values of -250, -50 or 50, 250. ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ I could use Random.Range(-250, 250) but this will also include the range between (-50, 50) which I don't want to Instantiate anything. ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ Also sadly most of the time numbers are not symmetrical as in my example, they are more randomly, like (-122, -30 and 40, 200). ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ What is the solution?
Answer by KronosAmon · Mar 24, 2020 at 04:29 AM
Okay took me some time but I actually achieved to do it myself. For anyone who needs the same thing here is the function I created (random number between two different range)
public float RandomRange(Vector2 lowerRange, Vector2 upperRange)
{
float realRange = Mathf.Abs(lowerRange.y - lowerRange.x) + Mathf.Abs(upperRange.y - upperRange.x);
float x = Random.Range(0, realRange);
if (x <= Mathf.Abs(lowerRange.y - lowerRange.x))
return Random.Range(lowerRange.x, lowerRange.y);
else
return Random.Range(upperRange.x, upperRange.y);
}
Your answer
Follow this Question
Related Questions
Random Generation problem GameObject 0 Answers
Use all variables from array (in Random.Range()) 2 Answers
Need help with specifics in Random.Range 1 Answer
how to randomly choose a value from array 3 Answers
Random bitmap generator 0 Answers