In this lesson, you will learn how to use the cross product to mathematically generate a vector that is perfectly perpendicular to two others.
What is the Cross Product?
While the dot product (which you learned previously) tells you how much two vectors "align" with each other, the cross product calculates a brand-new vector that sits at a 90-degree angle to both input vectors. Imagine holding your thumb and index finger apart to form an "L" shape; the cross product would be like a third finger sticking straight out from your palm, perpendicular to both.
Practical Applications
In Unity, we use this to find the "normal" (the direction a surface is facing) or to determine axes for movement.
- Surface Normals: If you have two vectors representing the edges of a flat polygon, their cross product gives you the "surface normal." This vector tells the lighting engine which way the surface is pointing, which is essential for rendering realistic shadows.
- Camera Movement: Imagine you want a camera to move along a path. If you know the camera's "Forward" direction and you want to know which way is perfectly "Right," you can calculate the cross product of the "Up" vector and the "Forward" vector. This ensures your movement axes stay perfectly perpendicular, preventing "tilting" or drift.
Calculating in Unity
Unity’s Vector3 struct provides a built-in method for this. You don't need to do the complex math by hand; you simply pass two vectors into Vector3.Cross.
// Define two vectors
Vector3 forward = transform.forward;
Vector3 up = Vector3.up;
// Calculate the vector perpendicular to both
Vector3 right = Vector3.Cross(up, forward);
// Now 'right' is perfectly perpendicular to both the Up and Forward vectors
When you perform this calculation, keep in mind that the order matters. Swapping the inputs (e.g., Vector3.Cross(forward, up)) will result in a vector pointing in the exact opposite direction. This follows the "Right-Hand Rule," a standard convention in 3D mathematics.
Key Takeaway: The cross product is a powerful tool to generate a third, mutually perpendicular vector, allowing you to define orientations and surface normals reliably in 3D space.