Game Development Reference
In-Depth Information
real operator *(const Vector3 &vector) const
{
return x*vector.x + y*vector.y + z*vector.z;
}
};
Notice that there is no in-place version of the operator (because the result is a
scalar value, and in most languages an instance of a class can't update itself to be an
instance of a different class: the vector can't become a scalar). I have also added a
full method version, scalarProduct , in case you are more comfortable writing things
longhand rather than remembering the slightly odd behavior of the * operator.
The Trigonometry of the Scalar Product
There is an important result for scalar products, which is not obvious from equa-
tion 2.3. It relates the scalar product to the length of the two vectors and the angle
between them:
a
·
b
=
a x b x +
a y b y +
a z b z =|
a
||
b
|
cos θ
[2.4]
where θ is the angle between the two vectors.
So,ifwehavetwonormalizedvectors,
a and b , then the angle between them is
given by equation 2.4 as
cos 1
· b
θ
=
a
Note the normalized vectors here. If a and b are just regular vectors, then the angle
would be given by
cos 1
· b
a
θ
=
|
a
||
b
|
If you so desire, you can easily convince yourself that equations 2.3 and 2.4 are
equivalent by using Pythagoras's theorem and constructing a right-angled triangle
where each vector is the hypotenuse. I'll leave this as an exercise for the skeptical.
The Geometry of the Scalar Product
The scalar product arises time and again in physics programming. In most cases it is
used because it allows us to calculate the magnitude of one vector in the direction of
another.
Figure 2.6 shows vectors in two dimensions (for simplicity—there is no difference
in three dimensions). Notice that vector
a has unit length. Vector b is almost at right
angles to
a , most of its length points away, and only a small component is in the direc-
tion of
a . Its component is shown, and despite the fact that b is long, its component
in the direction of
a is small.