Video Game Math: Vectors
In this installment, we’re going to talk about Vectors.
Vectors are arguably the most important kind of math for a game developer to understand, since so much of what we do revolves around them.
Segments, Rays, and Lines
In Geometry, you probably learned about some of the basic ways to express location, distance and direction – namely our standbys of Points (a single location), Segments (a part of a line connecting two Points), Rays (starts at a Point and goes in one direction forever) and Lines (goes forever in opposite directions).
One of the problems we have in computers is that they do really well with concrete concepts (“this thing is in this exact spot”) but they can’t handle abstract ideas (like “forever”) – how do you calculate “infinity”, anyway?
Another challenge we have is that we can add similar things (such as two decimal numbers – aka “floats”) but we have a harder time adding different things.
Fortunately, a lesser known concept in Geometry is the Vector. A Vector is similar to a Ray in that it indicates direction, but unlike a Ray it doesn’t have a starting point... they exist “everywhere” all at once. A good mental model is wind – if it’s 5mph north where I’m sitting, it’s 5 mph north a few feet away as well… it exists “everywhere”. (The science teacher in me wants to clarify – no, technically wind isn’t “everywhere” at the same rate. It just helps to think of it like that!)
Vectors look like coordinates, but they measure “change”, so if wind was blowing 5 units to the right and 8 units up, the Vector would look a lot like a coordinate – (5, 8) – but it’s measuring an “offset”. That also gives us a convenient way to express total distance.
If we approach it with the distance formula/Pythagorean formula we learned in the last installment, we could figure out that the total magnitude (distance) of the Vector is approximately 8.062.
If we tried to add an object at a Point (such as (4,9)) and move it along a Vector (such as (5, 8) above), in programming that’s difficult – you can’t add a Point and a Vector.
Think of the Point as a Vector that’s already happened – we store the object’s position as a Vector instead and offset it from our Origin.
Calculating Distance with Vectors
So its position is now a Vector, and the movement is now a Vector. If we add them both together, we get another Vector that represents the new position.
Vectors are also useful for a multitude of other things. For instance, we can use them to calculate the distance between two objects to figure out if a turret can hit a character, we can use them to see if an enemy in a stealth game can “see” the character (or if the character is outside their peripheral vision), and if an object hits a wall we can determine the angle that it’ll bounce off (or, in the case of Portal, what the new trajectory should be if we come out at some crazy angle).
Pretty much any time you see movement in a game, it’s using a Vector!