Game Development Reference
In-Depth Information
This is a method of measuring the length of the vector. It is a 3D version
of the famous theorem of Pythagoras that gives the length of the
hypotenuse of a right-angled triangle from the two other sides.
For example, if a = [6, 3, 2], then:
a
=
(6 * 6 + 3 * 3 + 2 * 2)
=
(36 + 9 + 4)
=
49=7
The dot product is a scalar; this simply means it is a number with a single
component not a vector. Given two vectors a = [ a x , a y , a z ] and b = [ b x , b y ,
b z ], the dot product is given by
a b = a x
×
b x + a y
×
b y + a z
×
b z
The dot product is very useful for finding angles between vectors. Since
we know that
a b =
a b cos
This implies that
a b
a b
= cos
Now we can calculate cos
directly. We can then use the inverse function
of cos , acos , to calculate the value of
. Here is a code snippet that will
pump out the angle between two vectors.
double angleBetweenVectors(VECTOR &v1, VECTOR &v2){
doubles,dot,mag1,mag2;
//Calculate the magnitude of the two supplied vectors
mag1=sqrt(v1.x*v1.x + v1.y*v1.y + v1.z*v1.z);
mag2=sqrt(v2.x*v2.x + v2.y*v2.y + v2.z*v2.z);
//Calculate the sum of the two magnitudes
s=mag1 * mag2;
//Avoid a division by zero
if (s==0.0) s=0.00001;
dot=v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
//Cos theta is dot/s. Therefore theta=acos(dot/s)
return acos(dot/s);
}