Dec
15

One of the biggest challenges for a game programmer is understanding how to represent position and movement in 2D and 3D space. In this tutorial I will teach you the basics of understanding vectors in 2D and 3D space.

Vectors

For the most part, we use vectors. In math and physics, vectors are usually represented by a direction (angle) and a magnitude (length).
See the diagram below (imagine the hypotenuse as an arrow):

Triangle

Theta (displayed as θ) is your angle in either degrees or radians (I will always talk about angles in degrees). The hypotenuse is the longest side of the triangle (your length or magnitude). The adjacent side is the side that touches the angle you’re working with, the opposite side is the side across from the angle. The adjacent and opposite sides are often your X and Y components, respectively.

In programming, we use the X and Y components so often that we just store and use them instead of the angle and magnitude.

Say we have a triangle with and angle and a magnitude, but we want the components. Here’s how to get them:

To get the components we use SOH CAH TOA, meaning this

sohcahtoa

so,
sine(θ)=O/H
cosine(θ)=A/H
tangent(θ)=O/A

*(θ just represents the angle)

keeping in mind that opposite will be our Y component and adjacent will be our X component, we come up with this

sine(theta) = Y/H
cosine(theta) = X/H

(we don’t need tangent at the moment)

and finally, this can be rearranged to make

Y = H × sine(theta)
X = H × cosine(theta)

Finally, Time for Some Code

We’ve got a good grasp on vectors now, so we need to make some code. How do we represent a vector in C++? Easy, like this:

struct Vector2D
{
    double x, y;
};

There, we now have a type Vector2D with the inner components ‘x’ and ‘y’.

Next, we have a vector. What can we use it for? The answer to that is “just about anything you want.” Vectors are used for so many applications that it’s nearly impossible to tell you what to use it for. The main things (in game programming) are position, direction and velocity.

2D Is So Old. I Need 3D.

So just add the Z component. It’s that easy (for now).

struct Vector3D
{
    double x, y, z;
};

Later, things won’t be so simple.

Coming Up Next…

We’ll be working with adding, subtracting vectors and multiplying and dividing scalars (magnitudes with no direction, aka regular numbers).

Posted by Jordan

One Response to “Vectors – Part 1”

  1. Chester R. says:

    This read is actually worthwhile, the content was certainly excellent! Keep up the great work.

Leave a Reply