Given a vector, how do i generate a random perpendicular vector?

135723-orthogonalvector.png
Given a vector A, how do i calculate a randomic vector that is perpendicular to A? I’ve been trying to figure this out myself for some hours but i can’t find a way.

Vector3 B = Vector3.ProjectOnPlane( Random.insideUnitSphere, A ).normalized;


Another solution

    B = Vector3.Cross( Random.insideUnitSphere, A ).normalized;

I haven’t compared the performances of the two solutions

there are some good answers here,
but as far as i can tell they all have a small chance of producing undefined results because they rely on being lucky in the choice of a second vector. if the second vector is very close to parallel (or anti-parallel) with A, there’s a problem. more than 99% of the time things will be fine, but eventually the result will be surprising. here’s a more stable approach.

// choose either the unit Up or Forward axis,
// depending on which one has the smaller dot() with A.
// ie, which one is more perpendicular to A.
// one of them is guaranteed to not be parallel (or anti-parallel) with A.
// any two vectors known to be perpendicular to each other will work fine here.
float   du = Vector3.Dot(A, Vector3.up);
float   df = Vector3.Dot(A, Vector3.forward);
Vector3 v1 = Mathf.Abs(du) < Mathf.Abs(df) ? Vector3.up : Vector3.forward;

// cross v1 with A. the new vector is perpendicular to both v1 and A.
Vector3 v2 = Vector3.Cross(v1, A);

// rotate v2 around A by a random amount
float degrees = Random.Range(0.0f, 360.0f);
v2 *= Quaternion.AngleAxis(degrees, A.normalized);

You want this :

B = Quaternion.LookRotation ( A ) * UnityEngine.Random.insideUnitCircle;

You need to figure out what “perpendicular” means. Is it towards the camera? Is it world up direction? is it a character or vehicle up direction?

You can use this to rotate a vector

//This will rotate your vector by a random angle around the world up axis.
vector = Quaternion.AngleAxis(Random.Range(0, 360), Vector3.up) * vector;

If you have two vectors then you can calculate a perpendicular vector, to both of the original vectors, using the cross product of the two vectors. Here is a 1 explaining the cross product if you are not familiar with it. The Unity cross product is explained here. Since you have one vector then you need to create a second vector that is random. That vector would have its origin at the one end of vector A and the other end defined by some random point around the origin. The second link has an example showing the use of the cross product that will also be applicable to what you are trying to do. All you need to do is define the second vector.