You’d like to understand what is meant by dot product and cross product.
In this recipe we’ll introduce the concept of vector dot product and cross product and how they might be used.
Dot product is an operation on two vectors that returns a scalar. It is often visualized as the projection of vector A onto vector B:
This is the formula for calculating the dot product:
θ is the angle between the two vectors and
||A|| is the magnitude of
This is very useful when both vectors are normalized (i.e. their magnitudes are
1), then the formula simplifies to:
Showing that the dot product is directly related to the angle between the two vectors. Since
cos(0) == 1 and
cos(180) == -1, the result of the dot product can tell you how closely aligned two vectors are:
See below for how we can apply this fact in a practical example.
The cross product of two vectors is a third vector that is perpendicular to both of them. Its magnitude is related to their magnitudes and the angle between them.
Once again, if we’re using normalized vectors, the result is simplified: it will be directly related to the angle and its magnitude will range from -1 to 1.
Since the cross product is perpendicular to both vectors, we would need to be working in 3D. In most 2D frameworks, including Godot, the 2D
Vector2.cross() method returns a scalar value representing the result’s magnitude.
Consider this animation, showing how the results of
Vector2.cross() change in relation to the changing angle:
This demonstrates two common applications of these methods. If the red vector is our object’s forward direction, and the green shows the direction towards another object:
> 0) or behind (
< 0) us.
< 0) or right (