Unity Vectors – What Every Game Developer Needs To Know About Vectors In Unity

Table of Contents

Unity Vectors – What Every Game Developer Needs To Know About Vectors In Unity

Reading Time: 7 minutes
Level: Beginner – Intermediate

Help Others Learn Game Development

Share on facebook
Share on twitter
Share on reddit
Share on linkedin

As soon as you start with Unity game development you will be bombarded with vectors. Most of the time you will use Vector2 for 2D games and Vector3 for 3D games.

So what are vectors and how can we use them?

Definition Of A Vector

Vectors are a fundamental mathematical concept which allows you to describe a direction and magnitude.

In math, a vector is pictured as a directed line segment, whose length is the magnitude of the vector and the arrow is indicating the direction where the vector is going:

Img 1
In game development, vectors are mainly used to describe the position of a game object, and to determine its speed and direction.
 
Vectors can be expressed in multiple dimensions, and Unity provides Vector2, Vector3 and Vector4 classes for working with 2D, 3D, and 4D vectors.
 
We will be mainly focused on Vector2 and Vector3 since they are used when developing 2D and 3D games with Unity game engine.
 

Vector2 And Vector3 In Unity

We already mentioned that in game development vectors describe the position of a game object, it’s the same with Unity.
 
A Vector2 object describes the X and Y position of a game object in Unity. Since it’s a Vector2, and it only describes X and Y values, it is used for 2D game development.
 
In a 2D game, if you move a game object with an x amount of units on the X axis, and x amount of units on the Y axis you will get the position of that game object:
 
Img 2
The same goes for a 3D game, except that you can move the game object on X, Y, and Z axis in the game space:
 
Img 3

The values for the axis are located in the Position property of the Transform component of course:

Img 4


The Magnitude Of The Vector

One of the things we use vectors for is to know the magnitude of the game object.

But what is magnitude of a vector?

The magnitude is the distance between the vectors origin (0, 0, 0) and its end point. If we imagine a vector as a straight line, the magnitude is equal to its length as we saw in the first image:

Img 1

To calculate the magnitude in math, given a position vector → v = ⟨a,b⟩, the magnitude is found by magnitude = √a2 + b2 (square root of a squared + b squared).

In 3D it works the same way, except that we have one more axis in the calculation magnitude = √a2 + b2 + z2 (square root of a squared + b squared + z squared).

But in Unity we simply do this:

				
					Vector3 testVector = new Vector3(10, 15, 20);
float testVectorMagnitude = testVector.magnitude;
				
			
Calling .magnitude on a vector variable will return the magnitude of that vector. And if you hover over the magnitude word in the code, you will see the explanation which states that magnitude will return the length of the vector, which is what we explained using the image above:
 
Img 5


For What Do We Use The Magnitude Of A Vector

The magnitude of a vector is used to measure the speed of the vector. I say speed of the vector but its actually the speed of the game object.

For example, if we are moving the game object using its Transform component, we can limit the movement speed using the magnitude of the vector:

				
					private float speedX, speedZ, moveSpeed = 10, maxSpeed = 100;
    Vector3 tempVector;

    void Update()
    {

        speedX = Input.GetAxisRaw("Horizontal");
        speedZ = Input.GetAxisRaw("Vertical");

        tempVector = transform.position;

        // if the speed of the vector is less than the
        // maximum allowed speed
        if (tempVector.magnitude < maxSpeed)
        {
            tempVector += new Vector3(speedX, 0f, speedZ) * (moveSpeed * Time.deltaTime);
        }

        transform.position = tempVector;
        
    }
				
			
The same goes for calculating the speed of a rigidbody. Since
 
				
					rigidbody.velocity
				
			
is a vector, we can get the speed of that rigidbody by calling
 
				
					rigidbody.velocity.magnitude
				
			
and we can use this information to limit the movement speed of the rigidbody the same we limited the movement speed of the Transform component in the example above.
 
We can also use the magnitude to calculate the distance between two vectors. If we have two vectors, a and b, then:
 
				
					(Vector A - Vector B).magnitude
				
			
is the distance between these two vectors. This is what the Vector3.Distance function actually does.
 

Squared Magnitude

As we already saw from the examples above, we can use .magnitude to calculate the magnitude of a vector in Unity.

What happens behind the scene is that Unity is doing that calculation using the math formula we saw, which is magnitude = √a2 + b2. And for 3D we would add the extra Z axis.

There is a faster way how we can calculate the magnitude of a vector which does not involve using square root in the operation and that is using sqrtMagnitude:

				
					float sqrtMagnitude = someVector.sqrMagnitude;
				
			

One thing that we need to be careful here is that this will calculate the magnitude without using the square root in the operation, which means it will return the magnitude squared e.g. the magnitude will 2x of its actual value.

So if we want to compare a distance between two vectors or the speed of the current vector we need to compare the squared values:

				
					private Vector3 vectorA, vectorB;
private float maxDistance, maxSpeed;

float vectorA_Speed = vectorA.sqrMagnitude;

// multiple the max speed with itself
// to make it a squared value
float maxSpeedSquared = maxSpeed * maxSpeed;

// comparing the maximum speed
if (vectorA_Speed > maxSpeed)
{
}

// calculating the distance between Vector A and B
float vectorAB_Distance = (vectorA - vectorB).sqrMagnitude;

// multiple the max distance with itself
// to make it a squared value
float maxDistanceSquared = maxDistance * maxDistance;

// comparing the distance between Vector A and B
if (vectorAB_Distance > maxDistanceSquared)
{
}
				
			


The Direction Of The Vector

One of the most common informations we need in a game is the direction of vectors which indicates in which direction a specific game object is going. This is used to move characters in the game, to create enemy AI and so on.

To get the direction of the vector we need to normalize it, and in Unity we normalize a vector like this:

				
					private Vector3 vectorA;
Vector3 vectorA_Direction = vectorA.normalized;

// or

vectorA.Normalize();
				
			

Using normalized or Normalize will give us the direction of the given vector.

Now you are probably asking what is the difference between the two?

Both lines of code will normalize(return the direction) the given vector, but using normalized on a vector will return a new version of the same vector that we can store in a new variable, and the original version of the vector will stay the same.

Using the Normalize function however, will normalize the vector is self e.g. it will change the original vector.

If you hover over the normalized word in the code you will see the following explanation:

Img 6

This means that the returned vector has a magnitude of 1 e.g. the length of that vector is 1, because this is how directions are represented in Unity.

For example:

				
					// right direction
Vector3 right = new Vector3(1, 0, 0);

// left direction
Vector3 left = new Vector3(-1, 0, 0);

// up direction
Vector3 up = new Vector3(0, 1, 0);

// down direction
Vector3 down = new Vector3(0, -1, 0);

// forward direction
Vector3 forward = new Vector3(0, 0, 1);

// backward direction
Vector3 backward = new Vector3(0, 0, -1);
				
			

Depending on the axis, adding 1 or -1 value will point to a certain direction. This is connect to Unity’s coordinate system which looks like this:

Img 7

As you can see, X is positive on right side and negative on the left, Y is positive up and negative down, and Z is positive forward and negative backwards.

This is why you see the positive 1 and negative 1 values for the vectors in the code example above.

What Is The Difference Between Vector Magnitude And Vector Normalize

From all the examples we saw so far for the vector’s magnitude and normalization, we can conclude that there is a difference between them and they are both used for different purposes.

The magnitude returns a float, its a single dimensional value expressing vector length. It looses directional information but provides the length information which we can use to control the speed of the vector.

Normalization is a bit of an opposite operation – it returns vector direction, guaranteeing that the magnitude of the resulting vector is one. This means it looses the magnitude information but preserves the direction information which we can use to know where the game object is moving or to move a game object in a specific direction.

What Is The Use Of Normalized Vectors

We already saw that normalizing a vector will return the direction of the vector, but why bother using normalization?
 
Why can’t we just use magnitude for the same purpose because using the magnitude we can calculate the distance between two vectors, which means we can calculate the distance between the current vector and the destination where we want to go, and we can use that information to move the game object in the desired direction.
 
While the claim above is true, we can calculate the length between vector A and vector B, but the problem is that vector A and B could be anywhere and at any distance, so magnitude could be anything.
 
Let’s say that we want to move object A 0.5 units towards object B. We can calculate the distance between object A and B using the magnitude, but we don’t have any means to calculate how to move object A towards object B by 0.5 units.
 
So in this case, we would subtract the distance between B and A and the multiple that by 0.5 and this is how we would move object A towards object B by 0.5 units.
 
This is how it would look like in the code:
 
				
					        private Vector3 vectorA, vectorB;

        // calculate the direction
        Vector3 movementDirection = (vectorB - vectorA).normalized;

        // move vector A towards vector B by 0.5 unitys
        vectorA += movementDirection * 0.5f;
				
			


Conclusion

The magnitude of the vector determines the length of that vector and we can use it to calculate anything related to speed of that vector.
 
This is useful if we want to control the speed of a game object or even calculate the distance between two game objects.
 
With normalization we get the direction of the specified vector. We can use this information to move game objects around and even create enemy AI.
 
If we want to move a game object from point A to point B, we can use normalization to determine the direction we need to go and then multiply the normalization value by x amount of units we want to move the game object which will make the game object move from point A to point B by the specified amount of units.
 

Leave a Comment