What is the best (fastest) way to compute two vectors that are perpendicular to the third vector(X) and also perpendicular to each other?
This is how am I computing this vectors right now:
// HELPER - unit vector that is NOT parallel to X
x_axis = normalize(X);
y_axis = crossProduct(x_axis, HELPER);
z_axis = crossProduct(x_axis, y_axis);
I know there is infinite number of solutions to this, and I don't care which one will be my solution.
What is behind this question: I need to construct transformation matrix, where I know which direction should X axis (first column in matrix) be pointing. I need to calculate Y and Z axis (second and third column). As we know, all axes must be perpendicular to each other.
To construct a vector that is perpendicular to another given vector, you can use techniques based on the dot-product and cross-product of vectors. The dot-product of the vectors A = (a1, a2, a3) and B = (b1, b2, b3) is equal to the sum of the products of the corresponding components: AβB = a1_b2 + a2_b2 + a3_b3.
The vectors β π΄ and β π΅ are perpendicular if, and only if, their dot product is equal to zero: β π΄ β β π΅ = 0 .
Explanation: Cross product of vectors A and B is perpendicular to each vector A and B. β΄ for two vectors βAandβB if βC is the vector perpendicular to both. =(A2B3βB2A3)Λiβ(A1B3βB1A3)Λj+(A1B2βB1A2)Λk .
How Do You Find a Vector Parallel to a Given Vector? To find a vector that is parallel to a given vector a, just multiply it by any scalar.
What I have done, provided that X<>0
or Y<>0
is
A = [-Y, X, 0]
B = [-X*Z, -Y*Z, X*X+Y*Y]
and then normalize the vectors.
[ X,Y,Z]Β·[-Y,X,0] = -X*Y+Y*X = 0
[ X,Y,Z]Β·[-X*Z,-Y*Z,X*X+Y*Y] = -X*X*Z-Y*Y*Z+Z*(X*X+Y*Y) = 0
[-Y,X,0]Β·[-X*Z,-Y*Z,X*X+Y*Y] = Y*X*Z+X*Y*Z = 0
This is called the nullspace of your vector.
If X=0
and Y=0
then A=[1,0,0]
, B=[0,1,0]
.
This is the way to do it.
It's also probably the only way to do it. Any other way would be mathematically equivalent.
It may be possible to save a few cycles by opening the crossProduct computation and making sure you're not doing the same multiplications more than once but that's really far into micro-optimization land.
One thing you should be careful is of course the HELPER vector. Not only does it has to be not parallel to X but it's also a good idea that it would be VERY not parallel to X. If X and HELPER are going to be even somewhat parallel, your floating point calculation is going to be unstable and inaccurate. You can test and see what happens if the dot product of X and HELPER is something like 0.9999.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With