- Home /
How to rotate a direction (create a direction from another direction)
Hi, I want a function that returns a random direction based on only two parameters: position and his normal.
private Vector3 generateRotation (Vector3 pos, Vector3 N)
{
// return R Vector3 (random direction)
}
The direction R create an angle of 90 degrees with N. The direction R has a random rotation around N. How can I generate R based only on position and his normal?
Simple Example:
input: pos=(0,0,0), N=(0,1,0) | output: R=(Random.Range(-1f,1f), 0f, Random.Range(-1f,1f)).normalized
Note: it must work on any normal. Example: N=(0,0,1) out R=(0,-1,0) or N=(.25,.25,.25) etc...
Answer by unity_ek98vnTRplGj8Q · May 12, 2021 at 08:21 PM
I'm not sure what you want to do with the position parameter, any vector always starts at the origin. As far as returning a random vector you have lots of options. The way I would go about it would just be to use the Cross Product. If you are not familiar with the cross product, it basically takes two vectors and returns a vector that is perpendicular to both. In your case you would want ANY vector that is perpendicular to your normal vector, so to randomize your cross product you could just randomize the second vector.
return Vector3.Cross(N, Random.onUnitSphere);
Technically there is the possibility here that the random vector is parallel to your normal vector, in which case the cross product would return the zero vector. To avoid this, we can just generate another random vector.
Vector3 output = Vector3.zero;
while(output == Vector3.zero){
output = Vector3.Cross(N, Random.onUnitSphere);
}
return output;
Thank you! I used: Vector3.Cross(N, Random.insideUnitSphere)
Answer by andrew-lukasik · May 12, 2021 at 08:13 PM
Adding position to a direction vector will make it a position vector (no longer a direction)
Vector3 GenerateRotation ( Vector3 normal ) => Vector3.ProjectOnPlane( UnityEngine.Random.onUnitSphere , normal ).normalized;
100 random rotations for
normal = new Vector3(1,1,1)
Thank you! I used: Vector3.Cross(N, Random.insideUnitSphere)