How can I find a Vector3
which is perpendicular to given Vector3
?
Maybe rotate the Vector3
90 degrees or something, is there a vector3 function that can do that?
The thing is, there is an infinite amount of vectors perpendicular to any given vector in 3D space. You need a second vector not parallel to the first one to find a vector perpendicular to them both, i.e. their cross product, since this way a plane is defined, which may have only one perpendicular line.
In Unity, cross product is computed by the static method Vector3.Cross()
.
-
This feels like a major milestone for me... I published my first game 9 years ago, but this is the first time I ever used
Vector3.Cross()
... and it worked beautifully the first time and I understand why. No longer is it arcane magic that I've merely heard of but am too scared to use. – ArtOfWarfare Feb 26 '20 at 0:49
To answer your original question: how to compute a vector perpendicular to another?
Let's call your vector p
and the vector we're looking for that is perpendicular to it q
. Note that there are an infinite number of vectors q
but we're just going to find one.
For perpendicular vectors the dot product is always 0
so we find the equation p · q = 0
which we can write as p.x * q.x + p.y * q.y + p.z * q.z = 0
. Now we're going to assign arbitrary values to q.x
and q.y
in order to fix one solution, let's pick q.x = 1
and q.y = 1
. Then we're left with p.x + p.y + p.z * q.z = 0
. Solving for q.z
gives us q.z = -(p.x + p.y) / p.z
.
In conclusion: the vector q = (1, 1, -(p.x + p.y) / p.z)
is perpendicular to p
.
-
Doesn't this fail for particular values of p? Like when its parallel to your arbitrary values? – Innovine Nov 4 '18 at 16:43
-
1If you consider infinite numbers as invalid, yes, there are some values that fail, namely values of
p
that havep.z = 0
. In this case you'll get a division by 0 and the valueq.z
will be infinite. To get around this you could check ifp.z
is 0 and then choose eitherq.x
orq.y
as your free variable. If all of the 3 values are 0 then you have the zero vector for which perpendicular is not well defined. – user7132587 Nov 6 '18 at 16:57
This perpendicular vector in 3D space is not unique. However, given another vector, you can obtain a new vector which is perpendicular to both of them.
Vector3 v1;
Vector3 v2;
Vector3 v3 = Vector3.Cross(v1, v2);
Vector3 newVector3 = originalVector3 * Vector3.right
gives you the originalVector but pointing to its right. This is relative though. Calculating quaternions might be more accurate and powerful, but it's far more complicated. – Andy Oct 30 '15 at 22:39