Calculating the Length of a Vector
Firstly, you will need to know how to calculate the length of a vector (known at the magnitude of a vector). This is exactly the same as calculating the distance between two points.
In 2D
Define your vector (x, y).
Length = SquareRoot(x*x + y*y)In 3D
Define your vector (x, y, z).
Length = SquareRoot(x*x + y*y + z*z)
Calculating the Dot Product
In 2D
Define your two vectors. Vector1 (x1, y1) and Vector2 (x2, y2).
DotProduct = (x1*x2 + y1*y2)In 3D
Define your two vectors. Vector1 (x1, y1, z1) and Vector2 (x2, y2, z2).
DotProduct = (x1*x2 + y1*y2 + z1*z2)
What is the meaning of the value returned by the dot product?
The value is the cosine of the angle between the two input vectors, multiplied by the lengths of those vectors. So, you can easily calculate the cosine of the angle by either, making sure that your two vectors are both of length 1, or dividing the dot product by the lengths.
Cos(theta) = DotProduct(v1,v2) / (length(v1) * length(v2))Values range from 1 to -1. If the two input vectors are pointing in the same direction, then the return value will be 1. If the two input vectors are pointing in opposite directions, then the return value will be -1. If the two input vectors are at right angles, then the return value will be 0. So, in effect, it is telling you how similar the two vectors are.
Backface culling
When deciding if a polygon is facing the camera, you need only calculate the dot product of the normal vector of that polygon, with a vector from the camera to one of the polygon's vertices. If the dot product is less than zero, the polygon is facing the camera. If the value is greater than zero, it is facing away from the camera.