Game Development Reference
In-Depth Information
Unity is doing the calculations in terms of the vector's x and y coordinates, but you can see it is
following the same formula with a, b, and c from geometry class (Fig 2-35 ):
(x, y)
magnitude
y
c
b
x
a
c = a + b
magnitude = x 2 + y 2
2
2
Pythagorean Theorem
Vector2.magnitude
Figure 2-35. Vector2 magnitude derived using the Pythagorean Theorem
As an example, find c when a = 3 and b = 4. First, a 2 = 9 and b 2 = 16. Add them together to get 25,
then take the square root of 25 to find the length c = 5. Now let Unity do the same calculation for the
Vector2 (3, 4) . Edit your script to the following:
#pragma strict
function Start () {
var myVector : Vector2 = Vector2(3, 4);
Debug.Log(myVector.magnitude);
}
Play to test and the Console displays the magnitude of 5.
Look again at the Vector2.magnitude description. Unity is giving you a tip: when you want to
compare the magnitude of two vectors, you can also use sqrMagnitude . Either way you can
determine if the magnitude of one vector is larger or smaller than the other, but using sqrMagnitude
will work faster. Whether in the scripting references or the Unity Forums, you will often see
comments regarding speed. Games take a lot of computational power, so the faster or more
efficiently any individual computation can be accomplished, the smoother your game will function.
At the bottom of the Vector2 scripting reference, you'll also find some handy mathematical and
comparison operators you can use (Figure 2-36 ).
Figure 2-36. Vector2 operators described in the Unity Scripting Reference
 
Search WWH ::




Custom Search