Game Development Reference
In-Depth Information
Click here to view code image
arrowVector = objective.position - player.position
Length, Unit Vectors, and Normalization
As mentioned, vectors represent both a magnitude and a direction. The magnitude
( length ) of a vector is typically denoted by two lines on either side of the vector's
symbol, such as
. The formula to calculate the length is as follows:
This
may
seem
very
similar to the distance formula
, and that's because we are using it! We are
calculating the distance from the origin to the position at which the vector is point-
ing.
Although it is not as much of an issue as in the past, taking a square root is still a
relatively expensive operation. If you absolutely need the actual length of a vec-
tor for a numerical calculation, there is no way to get around the square root.
However, suppose you only want to know whether object A or object B is closer
to the player. In this case, you could make a vector from the player to object A as
well as a vector from the player to object B. It would be possible to then take the
lengths of the vectors and see which one is shorter. But because the length cannot
be negative, it is also true that the comparison between the square of the length is
logically equivalent:
Therefore, the expense of a square root can be avoided in instances where only a
comparison is necessary. If we square both sides of the length equation, we're left
with the length squared :
Hand in hand with length is the idea of a unit vector , or a vector whose length is
one. A unit vector is typically represented with a “hat” above the vector's symbol,
as in . Converting a non-unit vector into a unit vector is known as normaliza-
tion . To normalize a vector, each component must be divided by the length of the
vector:
Search WWH ::




Custom Search