- Home /
Random perpendicular vector3 after rotation
I am generating random vectors3 (lets name it R), which would be perpendicular to given vector3 (lets name it A). If vector A is defined as:
Vector3 A = new Vector3(0f,1f,0f);
I can easily get any random vector3 which would be perpendicular to A by:
Vector3 R = new Vector3(Random.Range(-1f,1f), 0f, Random.Range(-1f,1f));
How I could create random vector R which would be perpendicular to any vector in 3d space?
Answer by robertbu · Oct 14, 2014 at 04:05 PM
Given any two non-parallel vectors, you can generate the perpendicular by Vector3.Cross(). The direction of that vector will depend on the order you pass the two parameters in the Cross() call.
To add to this, if you only have 1 vector (i, j, k), then there are an infinite number of perpendicular vectors, all of which line on the plane of equation ix + jy + kz = 0, you can then solve that equation to find related x, y, z values for a random perpendicular vector, for example:
Vector3 v = Vector3.zero;
while(v == Vector3.zero){
v = new Vector3(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f));
}
Vector3 vPerpendicular = Vector3.one;
if(v.x != 0){
vPerpendicular.x = -(v.y*vPerpendicular.y + v.z*vPerpendicular.z)/v.x;
}else{
vPerpendicular.x = Random.Range(0.0f, 1.0f);
}
if(v.y != 0){
vPerpendicular.y = -(v.x*vPerpendicular.x + v.z*vPerpendicular.z)/v.y;
}else{
vPerpendicular.y = Random.Range(0.0f, 1.0f);
}
if(v.z != 0){
vPerpendicular.z = -(v.y*vPerpendicular.y + v.x*vPerpendicular.x)/v.z;
}else{
vPerpendicular.z = Random.Range(0.0f, 1.0f);
}
Debug.Log(vPerpendicular);
vPerpendicular will be a random vector in the plane for which v was the normal
Hope that helps!
Cross product with any other random vector seems to be working. Thanks.