Vectors are the basis of most 3D math used in games. Vectors are used to represent position, direction, velocity, acceleration and more.
This article covers the basics of vectors: what are they, and what are they useful for.
For our purposes, a vector is simply a group of of related numbers. A 2D vector contains two values, x and y. A 3D vector contains three values, x, y, and z.
Mathematicians usually write vectors vertically, like this:
However, on computers, it's more convenient to write vectors like this:
(x, y, z)
(0, 1, 2)
(0, 180 , -90)
(0.1, 0.4, 0.5)
In Unity C#, we create a 2D Vector with the Vector2 class, like this:
//declaring a new Vector2 (the unity class for 2D vectors) with x=1 and y=0
Vector2 someVector = new Vector2(1,0);
Debug.Log(someVector.x); // prints the x component of someVector, which is 1
Debug.Log(someVector.y); //prints the y component of someVector, which is 0
And we create a 3D vector with the Vector3 class, like this:
//declaring a new Vector3 (the unity class for 3D vectors) with x=1, y=2, z=3
Vector3 some3DVector = new Vector3(1,2,3);
Debug.Log(some3DVector.x); // prints the x component of someVector, which is 1
Debug.Log(some3DVector.y); //prints the y component of someVector, which is 2
Debug.Log(some3DVector.z); //prints the z component of some3DVector, which is 3
Vectors can be used to represent a direction, relative to the x, y, and z axes.
Notice how the X and Y values change as the arrow points in different directions.
What happens to the values when the arrow aligns with the x or y axes? What happens when the arrow points at an oblique angle?
Can you think of common game features where it would be useful to keep track of a direction in space?
In this example, our vector has an x value of 3, and a y value of 4.
If we plot the vector as an arrow, it points:
Together, the x and y components of the vector representing a direction pointing up and to the right at a fairly steep climb; a 60 degree incline, to be exact!