Fundamentals of Vector Math in Game Development
Learn the Fundamentals of Vector Math in Game Development. Get a quick and deep insight on the meaning of vectors, vector operations, uses in Game Development, types of vectors, and application of Vector Math in Game Development especially in Unity.
Making games is always fun. It’s quite an interesting journey how we develop a game from scratch and craft some beautiful experiences throughout. This journey of Game Development includes various aspects of making a game like for example Graphics Designers making awful visuals, Sound Designers creating some breathtaking music, Programmers giving life to the game, and many more things. But have you ever wondered even after Good Graphics, Game Design, and Sound Design, why a game still lacks the proper game feel? Well, that goes straight to the Mechanics of the game. Game Mechanics primarily decides how interactable and impactful your game feels and this depends on programmers how to join all the pieces together. A well-balanced game with good visuals, music, game design, and good mechanics would make up to the top charts with good retention over the period. The mechanics of the game completely depends on the game type and vary accordingly, for example, for some games Physics plays a heavy role in the entire game, and for others, it’s just Transform, the logic, and Animation that does the job. But now a major question from most of the beginners to answer here is, do we really require Math in Game Development? You might have guessed the answer from the above details but to clear again the answer is quite simple, Yes, we do require but initially, the level would be much lower. The basics of Math would initially help all the beginners to kickstart their journey in the field of Game Development. The First and Foremost essential thing in the field of Math and Game Development is Vectors, not just in Games but Vectors have many real-world applications and are considered to be one of the base pillars in the field of Math. So here we will be discussing the Fundamentals of Vector Math and its application in Game Development.
A vector is a quantity or an object that has both direction and magnitude. Geometrically it is represented by a line segment where the length of the line denotes the magnitude and the arrow gives us the direction. It is the fundamental concept required while dealing with motions in physics. In the field of Game Development, Vectors have a wide range of practical applications, and mastering it can make up some really natural mechanics in games.
Although most of the Game Engines today, for example, Unity, Unreal, CryEngine, etc have their own advanced physics to work with but still, Game Developers require to have some decent knowledge to interact with the Engine API and operate it as per the needs. On a general basis, Vectors are used in games to describe and manipulate some fundamental properties like position, rotation, and scale. More often, Game Developers use Vectors to determine the position of an object, the speed of a moving entity, the length of a certain object, and the distance between two specific positions. Further, it also helps in getting the direction which is mostly used in games having automatic following mechanics.
The vector contains one or more dimensions depending upon the space and the scope of the context. For example, a 2D space generally deals with the 2D Vectors namely x and y while 3D space deals with the 3D vectors, x, y & z. Game Engine provides support to work with 2D, 3D, and 4D Vectors upon the requirement which carries essential information like position data, rotation data, scale data, color data, or data in any other forms. A 4D vector in Game Engines like Unity is often used to store one additional quantity for example if you are dealing with colors then Vector4 can be helpful to store Red, Green, Blue, and Alpha values. So, you can use Vectors in your games to store quantities and can later use them for some complex calculations.
Not just quantitative data but Vectors are primarily useful to get the direction in space. Whether you are in 2D Space or you require to calculate in a 3D Space, Vector simplifies your job in seconds. This is the reason why if you want to make games or you are already making a game, then Vector is your long-run and most valuable friend in this journey. So far, we got to know about the basic meaning of Vectors and their importance in the field of Game Development, now let’s dive a little deeper into the topic and see some applications.
P.S - All the examples and Applications shown are done in Unity Engine, however, the logic is still the same for all other engines and software as well.
Vectors for Positions
Here in this section, we will see the role of Vectors for Position in Games. As we just discussed above, the Vectors can be helpful to store data in various forms from 1D Vector to 4D Vector depending upon requirement in the Game Development phase. Let’s understand how it is done, for example, let’s consider an object naming “A” in 2D space. The 2D space has 2 coordinates, x going horizontally and Y going Vertically perpendicular to X. As the Object “A” is in a 2d space the location or the position of the Object would be denoted by the help of x and y coordinates. Let say, the Object “A” is 3 units right to the origin and 4 units up from the origin, where the position of the Origin is universally considered as O (0,0). This notation can be written as A(x,y) which can also be written in terms of value as A(3,4). This means the position of the Object A is at (3,4), i.e., Object A is 3 Units Right from Origin and 4 Units Up from the Horizontal Line or the Origin. Now, this can be stored as a 2D vector as we are dealing with 2 quantities and in 2D Space. So, the position of the Object “A” in vector form would be Vector2(3,4), where Vector2 represents the 2D vector and (3,4) tells us the coordinates of the position. Mathematically this same thing can be expressed in terms of expression which is shown below-
A = 3i + 4j
Where I and j are the representation of the space x and y.
So, this was the example for the position of an object in a 2D space, but what if the same object is in a 3D world? Well, the answer is pretty easy and self-explanatory. A 2D Space means 2 coordinates that are x and y while the third space z being 0, which means we are dealing with the length and breadth of an object but not considering the depth/width of it. So if an Object is in a 3D Space then the position representation would be in 3D Vector format, i.e Vector3(x,y,z). So, for the given example, let the Object is at the same x and y position but 5 units depth or away from the Origin O (0,0,0). Then the Object position in Vector format would be Vector3(3,4,5) in 3D Space. This means we added a 3rd dimension z which represents the depth of the object from the center. Mathematically this would be written as,
A = 3i + 4j + 5k
Where I, j, and k are the representation of the space x, y, and z respectively.
Here in this part, we got to know how Vector is used in Position. But this is just a simple case, there’s even a lot more ahead, for example, using the position, we can do many things, like calculating the speed of the moving object, determining the distance of two objects, and many more. Now let’s see how we can use Vectors for Direction.
Vectors for Direction
You must have seen many games having automatic follow mechanics, and you might have once thought about how it is being crafted and done so seamlessly. The answer is quite simple again, Vector. Vector helps us in getting the direction from one point to other. As we have seen above, geometrically it is represented as a line segment with the arrow showing us the direction. Now if we need to determine the direction of a vector within two given positions then the resultant vector is the answer. Mathematically the resultant vector is the line joining from the position of Vector A to Vector B and is further expressed as, C = B - A. This will give us the direction towards Vector B from Vector A. The logic applies the same for the Game engines where we tend to calculate the direction with the help of the resultant vector. So let us have two Objects A & B with positions A (4,5,6) and B (1,2,3) then the line joining A and B would be the resultant vector showing the direction from A to B. In the Game Engine first, we need to head towards Object B, which can be done by,
var heading = A.position - B.position;
Now we are pointing towards Object B. Also, you can notice this gives us the distance if we tend to get the magnitude of the heading variable, so,
var distance = heading.magnitude;
This distance will be helpful to get the direction if we normalize it with its own direction or using normalize the function of Unity,
var direction = heading/distance;
This is how we can give a player direction to move from Object A position to Object B position.
Vectors for Speed & Velocity
Vectors are also primarily used to ascertain the velocity of a body to move. Not just velocity but it also accounts for the force we apply to a body. For example, in Angry Birds, the projectile that we see is achieved by a vector having a direction and magnitude to shoot the bird forward with an angle. The same goes for other games having motion and physics. Let’s see a quick example to visualize the use case of Vectors for Speed and Velocity.
First, let’s position our object in the center and add a certain force to the object to move around the scene.
To move forward let’s give a force to the object with a vector having Z direction.
Object.AddForce = speed * new Vector3(0,0,1);
This would move the object towards the z-direction as the other two axes are 0. Similarly, to move the object towards left, right, up, and down the code is pretty simple,
Object.AddForce = speed * new Vector3(-1,0,0); // Left Object.AddForce = speed * new Vector3(1,0,0); // Right Object.AddForce = speed * new Vector3(0,1,0); // Up Object.AddForce = speed * new Vector3(0,-1,0); // Down
Now let’s check if we require a diagonal movement. This would be fairly simple too, let for example we want to move our object towards the right and up as well, so our code would be,
Object.AddForce = speed * new Vector3(1,1,0);
This way we can move our object towards positive x-direction and also move it upwards making our object move diagonally.
So far, we have discussed a few areas in which Vectors could be helpful in making our life easier with small concepts and a few lines of code. It’s time to dive deeper into the topic and learn a little more about Vectors, their type, and applications which would be beneficial ahead in your Game Development Journey.
Scalar quantity refers to a quantity having only magnitude. Unlike Vectors having both the magnitude and direction, scalar quantities are described as only storing the magnitude of a particular object. For example, an integer or float are scalar quantities having value as the magnitude.
Unit Vector is also known as Direction Vector which can be defined as a vector with magnitude 1.
As the name suggests, the Null can be defined as a vector with a magnitude of 0.
A normal vector is a vector that is perpendicular to the surface at a given point. Normal Vectors are essentially used in the area of Graphics and other Geometrical calculations.
Now the Normalized Vectors or Unit Normal Vectors can be defined as Normal Vector with unit length i.e., 1. This is extensively used in Games to minimize the calculation error and get optimal results.
Vector Coordinate System
It’s important to recognize the orientation and coordinates your Game Engine is using in order to stick to the convention throughout the game-making process. This would ensure a low level of error while doing Vector Operations. Generally, there are two rules to check your Game Engine’s coordinate System, the Left-Hand Thumb Rule, and the Right-Hand Thumb Rule.
Here in this section, we would be learning about Vector Operations and how we can use them in our games. Learning Vector Operations is crucial to deal with the calculations while making a game. However, the Vector Operations are quite simple and need some practice to use in game development.
The first thing we would be learning is the addition of two Vectors. Vector addition is quite a simple operation which is just like a normal math addition process but with a slight twist.
For example, let we have two vectors, A=3i+4j and B= 5i+6j which can be written as A = new Vector2(3,4) and B= new Vector2(5,6). Then the addition of two vectors would be Result = Vecor2(8,10);
The logic behind this is pretty simple, the addition of the vectors works like normal addition but of the same axes, this means we would add up the x-axis value of A with the x-axis value of B to get the X-axis result and the same goes for the y-axis, we will add up y-axis value of A with y-axis value of B to get Y-axis result individually. Representing in simple form would be,
A = (3,4) B = (5,6) Result = (3+5,4+6) i.e., Result = (Ax + Bx, Ay + By) Result = (8,10)
So, all we need to do is add up the values of the same axes and for the result, which is fairly simple just like normal scalar addition.
Vector Subtraction is widely used in games to find out the distance and the direction of an object. The magnitude defines the value or the distance whereas the sign of the magnitude (Positive or negative) defines the direction of the object. Just like the Vector Addition, Vector Subtraction is also that simple but with a little bit of logic.
Let’s take the above Vectors, for example, to get the subtracted result we need to subtract the vector A from Vector B, this means,
A = (3,4) B = (5,6) Result = B - A Result = (5-3, 6-4) i.e., Result = (Bx - Ax, By - Ay) Result = (2,2)
As the values are positive the Vector is directing towards the positive x and y-axis.
Vector Dot Product
The Dot Product of Vectors is quite essential in getting the relationship between two objects both in-game and in the real world. The Vector Dot Product helps us to determine if an object is facing towards a particular direction as it plays a crucial role as a directional vector. With the help of the Dot product, we can check the orientation/rotation of an object. This is done by determining the properties of a scalar value it returns, for example, if the dot product of two vectors is 1 then the normal is facing in one direction, if 0 then the normal are perpendicular and if -1 then the normal are at opposite direction as shown in the image below.
This value is derived by multiplying the magnitude of the two vectors with the cosine of the angle between the two Vectors. After normalizing both vectors we get a scalar value that gives us the direction of the Vector. As it is based on the cosine function the value would range from -1 to 1.
Again, this is also a simpler operation just like addition and subtraction. Here, we just need to multiply the values with the same axes and then lastly add up to get the result.
Mathematically, it is represented as,
Vector A (x,y,z) Vector B (x,y,z) Vector A.B = (Ax * Bx) + (Ay * By) + (Az * Bz) Or, Vector A.B = |A| * |B| * cos(θ)
Where, |A| & |B| is the magnitude of Vector A and B respectively and θ is the angle between two Vectors. However, the result of both the approach would b fairly the same.
In Unity, we can use directly the Vector.Dot(Vector A, Vector B) to get the result. Generally, the speedometer of a car is more likely to work on the principle of Dot Product while measuring the rotational speed of the wheels. So to calculate the forward speed we can use,
var fwdSpeed = Vector3.Dot(rigidbody.velocity, transform.forward);
This would account for the speed in the forward direction.
Now another important use case of the Dot product is to get the angle between two objects. This could be a little tricky task but easy to do. As we are on a Cosine range we can use the Acos function on the Dot product to get the angle, for example,
Var angle = Mathf.Acos(fwdspeed) \* Mathf.Rad2Deg);
So, this way we can calculate the angle of two vectors. Specifically in Unity using Dot product this was is super-efficient than calculating it using Mathf.cos.
Vector Cross Product
Vector Cross Product is another essential operation in the field of vectors that is quite different than other operations we have seen this far. These are most likely to be useful in 3D space where we tend to get a Vector as a result while doing Cross Product. Just like the Dot Product, this can be used majorly for rotational purposes in 3Daxes. The result of the Cross Product gives us a perpendicular vector to the Two given Vectors which can be viewed by using the Left Thumb Rule in Unity. The Vector Cross product is highly essential in getting the Normal Vector using the given Vectors. As we have already discussed above that the Normal Vectors are perpendicular to the given surface, the same thing can be obtained with the help of two given vectors.
Just like the Dot Product calculation, Cross product magnitude can be derived by multiplying the magnitude of two Vectors with the Sine of the angle between the two Vectors. This gives us again a scalar value which could be essential ahead. It’s a little complex but simple to understand.
Vector A (x,y,z) Vector B (x,y,z) Vector A*B = |A| |B| Sin (θ)
Where, |A| & |B| is the magnitude of Vector A and B respectively and θ is the angle between two Vectors.
In Unity, we can get the Normal Vector using the Two Vectors, For example,
Vector3 a; Vector3 b; Vector3 c; Vector3 side1 = b - a; Vector3 side2 = c - a; Vector3 normal = Vector3.Cross(side1, side2);
Further, we can normalize the Vector using the Vector normalized property or by dividing it up by its own magnitude.
float perpLength = normal.magnitude; normal /= perpLength;
Check Unity's Official Blog to know more about Vectors.
Further, this example can be visualized using a real-life game scenario where we want to rotate our players' gunpoint to an enemy standing on the side. The Cross product of the two Vectors, one pointing toward the enemy and one going straight with the gunpoint will result in a third vector towards up perpendicular to both, which would give us the axis of rotation. By getting the axis of rotation we can use it to rotate it. For easier visualization of the resultant vector use the Left-hand thumb rule.
So far, we learned about all the necessary vector operations with examples and also discussed how we can use them in Unity. These fundamentals of Vector Math would help you ahead to kickstart your journey in Game Development while understanding the basic math required while developing games. As mentioned earlier, in today’s date most of the Game Engine already provide enough solutions to deal with real-life physics and pre-calculate complex maths for you, however, game developers are still required to possess some average knowledge to interact with the game Engine API and manipulate it according to the game needs. As we are taking Unity Game Engine for reference in this blog, Unity provides a variety of pre-defined operations which we can use in just a single line of code. It has both Static Methods and properties which can be used to solve some complex calculations in just a few lines of code. Here are a few most important static methods required while making Games,
Vector3 has been taken into account for this example as it is most commonly used
Angle - Returns the angle in degrees between from and to.
ClampMagnitude - Returns a copy of the vector with its magnitude clamped to maxLength.
Cross - Cross Product of two vectors.
Distance - Returns the distance between a and b.
Dot - Dot Product of two vectors.
Lerp - Linearly interpolates between two points.
LerpUnclamped - Linearly interpolates between two vectors.
Max - Returns a vector that is made from the largest components of two vectors.
Min - Returns a vector that is made from the smallest components of two vectors.
Move Towards - Calculate a position between the points specified by current and target, moving no farther than the distance specified by maxDistanceDelta.
Normalize - Makes this vector have a magnitude of 1.
RotateTowards - Rotates a vector current towards the target.
Slerp - Spherically interpolates between two vectors.
SlerpUnclamped - Spherically interpolates between two vectors.
SmoothDamp - Gradually changes a vector towards a desired goal over time.
These Static Methods will make our life simpler as they would not just reduce the calculation steps but would also primarily help us getting our code well optimized and give us prime ability to solve physics and math problems efficiently.
Although, we have discussed Vectors and its application in Unity thoroughly, let’s take a last look at how important and widely it is used in Unity,
1. Used to define the coordinate system
2. Used in Raycast
3. Used for all Physics-related Applications
4. Used to calculate Geometry Calculations
5. Used to Calculate Normal
6. Used for Transform, Rotation, and Scale
7. Object Tracking and Angle Determination
As of now, it’s quite evident to know that the use of Vectors is everywhere and the importance of Vectors is extreme. Not just Unity but every Game Engine has the use of Vectors. So, in this article, we discussed all the aspects of vectors in Game Development and also learned the fundamentals of vector math in Game Development taking Unity as a referral engine. The prime goal of this article is to help beginners and our readers to understand the basics of Vector Math and how it’s required in the field of Game Development. Hope this article explains well about the given context and lays off a good baseline to start with. Stay tuned for such informative content and do let us know If it helped you in your Game Development Journey.