# How to get a random Vector 2 within a range

I'm working on a game and I need the objects that get spawned to launch within a range of angles, so like in the horrible 2 second paint image seen below, I need to grab a random vector within that range of arrows, and then the ball will go off in that direction. I'm just not sure how to get a vector within a range like that. This is in C# and Unity, the game is 2D. Any ideas?

I would write a function that uses a random rotation value and converts it into a Vector2 using sin/cos.

The following function takes the angle range (in radians) for how big you want the range of values to be in, and a starting angle if you want it offset.

C#

public Vector2 RandomVector2(float angle, float angleMin){
float random = Random.value * angle + angleMin;
return new Vector2(Mathf.Cos(random), Mathf.Sin(random));
}


JavaScript

function RandomVector2(angle, angleMin){
var random = Math.random()*angle+angleMin;
return [Math.cos(random), Math.sin(random)];
}


Sample use

RandomVector2(3.1415, 0.0); // random angle between 0-180 degrees
RandomVector2(3.1415, 3.1415); // random angle between 180-360degrees

• Ok so this is suuuuuper close. I have it set up so I'm setting the velocity of the object to the return value of RandomVector2(). The balls spawn and launch in the correct directions, but they are very slow. What would I need to do to increase the speed. I get confused about how a simple Vector2 relays information about both speed and direction. Aug 23, 2018 at 1:50
• This method will return a normalised Vector2() meaning its length with always be 1. If you want to increase the length you can use: Vector2 vec = RandomVector2() * 2.0; // I think this is the syntax Aug 23, 2018 at 2:30

The other answer's here work fine. If you want a "vector only" approach you could use a Lerp function. Basically, generate a new vector that blends between two others based on a random value.

It's quick, intuitive, and you get reliable results. Also you're just using a built in vector math call, so you don't have to worry about implementation issues.

Vector2 RandomV2(Vector2 min, Vector2 max){
return Vector2.Lerp(min,max, Random.value).normalized;
}


Personally I find the following approach more intuitive:

1. Generate the random angle as a float like
float angle = Random.Range(minAngle, maxAngle);
1. Then use a function like
// https://answers.unity.com/questions/823090/equivalent-of-degree-to-vector2-in-unity.html
public static Vector2 DegreeToVector2(float degree)
{
}
{
}
offsetLeft = -3;

Then after that you could probably use a velocity function rb.velocity = new Vector3(randomX, gameobject.trasform.position.y + 3, 0); I havent really tried this code but maybe that will maybe give an idea