Home>

### [unity3d] how to randomly get one vector perpendicular to the normal vector

As the title says, I don't know how to implement it due to lack of mathematical knowledge and unfamiliarity with Unity's vector calculation.

When I looked up how to get the normal vector from two vectors, I found a method, but I don't know the opposite.
I hope you can assume the position of the plane so that it passes through the origin.
Thanks for your cooperation.

>>>I've solved it, so I'll lightly paste the method below.

``````// Final method form
Vector3 GetPerpendicularVec (Vector3 vec) {
var randomNum1 = Random.Range (-1f, 1f);
var randomNum2 = Random.Range (-1f, 1f);
while (randomNum1 == 0&randomNum2 == 0) {// About the possibility that the length of the vector is 0
randomNum1 = Random.Range (-1f, 1f);
randomNum2 = Random.Range (-1f, 1f);
}
float number;
Vector3 targetVec = Vector3.zero;
// Extract one random vector from the plane
if (vec.x! = 0) {
number = (-randomNum1 * vec.y --randomNum2 * vec.z)/vec.x;
targetVec = new Vector3 (number, randomNum1, randomNum2);
} else if (vec.y! = 0) {
number = (-randomNum1 * vec.x --randomNum2 * vec.z)/vec.y;
targetVec = new Vector3 (randomNum1, number, randomNum2);
} else if (vec.z! = 0) {
number = (-randomNum1 * vec.x --randomNum2 * vec.y)/vec.z;
targetVec = new Vector3 (randomNum1, randomNum2, number);
} else {
Debug.LogAssertion ("The length of the given vector is 0");
}
return targetVec.normalized;
}``````
• Answer # 1

A normal vector is originally a vector for defining a plane.
Once the normal vector and any one point on the plane are determined, the plane is determined and any vector on the plane is perpendicular to the normal vector.

When the normal vector is (a, b, c), the equation for the plane containing the origin (0,0,0) is
It becomes ax + by + cz = 0.

If there is no limit to the length of the vector to be obtained, x and y can be randomly determined, and only z can be obtained from the above formula to obtain a vertical vector.
However, if the length is 0, it has no meaning as a vector, so x = 0 and y = 0 should be excluded.