Game Development Reference
In-Depth Information
One thing that's left out from Figure 8-1 is the units the vector components have. We have to
make sure that these are sensible (for example, Bob's velocity could be in meters per second,
so that he travels 2 m to the left and 3 m up in 1 s). The same is true for positions and distances,
which could also be expressed in meters. The direction of Bob is a special case, though—it is
unitless. This will come in handy if we want to specify the general direction of an object while
keeping the direction's physical features separate. We can do this for the velocity of Bob, storing
the direction of his velocity as a direction vector and his speed as a single value. Single values
are also known as scalars . The direction vector must be of length 1, as will be discussed later in
this chapter.
Working with Vectors
The power of vectors stems from the fact that we can easily manipulate and combine them.
Before we can do that, though, we need to define how you represent vectors. Here's an ad hoc,
semi-mathematical representation of a vector:
( )
v
=
x, y
Now, this isn't a big surprise; we've done this a gazillion times already. Every vector has an x and
a y component in our 2D space. (Yes, we'll be staying in two dimensions in this chapter.) We can
also add two vectors:
(
) (
) (
)
c
=+=
a
b
a.x, a.y
+
b.x, b.y
= +
a.x
b.x, a.y
+
b.y
All we need to do is add the components together to arrive at the final vector. Try it out with
the vectors given in Figure 8-1 . Say you take Bob's position, p = (3,2), and add his velocity,
v = (-2,3). You arrive at a new position, p ' = (3 + -2, 2 + 3) = (1,5). Don't get confused by the
apostrophe behind the p here; it's just there to denote that you have a new vector p . Of course,
this little operation only makes sense when the units of the position and the velocity fit together.
In this case, we assume the position is given in meters (m) and the velocity is given in meters per
second (m/s), which fits perfectly.
Of course, we can also subtract vectors:
( ) ( ) (
)
c
=−=
a
b
a.x, a.y
b.x, b.y
= −
a.x
b.x, a.y
b.y
Again, all we do is combine the components of the two vectors. Note, however, that the order in
which we subtract one vector from the other is important. Take the rightmost image in Figure 8-1 ,
for example. We have a green Bob at pg = (1,4) and a red Bob at pr = (6,1), where pg and pr
stand for position green and position red, respectively. When we take the distance vector from
green Bob to red Bob, we calculate the following:
( ) ( ) ( )
d
= − = − =−
pg
pr
1, 4
6, 1
5, 3
Now this is strange. This vector is actually pointing from red Bob to green Bob! To get the
direction vector from green Bob to red Bob, we have to reverse the order of subtraction:
( ) ( ) ( )
d
=−= − =−
pr
pg
6, 1
1, 4
5, 3
 
Search WWH ::




Custom Search