# Vector Basics

A vector is a very common concept mentioned in math, physics, and computer science. Understanding what they are and how to use them is essential in 3D game design.

## Definition

In math and physics, a vector is a directional arrow that represents a certain length and direction. In computer science, a vector is a type of data structure that can store multiple numbers. Those numbers correlate to the directional arrow’s end position assuming the arrow started at the origin. Here’s an example of a 2D vector represented by the red arrow and the ending position coordinates (X=5, Y=5).

## Use Cases

In programming, vectors are most commonly used to account for an object’s position and speed. Take this example of a player currently at the red vector position (5, 5) and is moving at a speed equal to the green vector (0, 4). The speed vector is using the player’s position as a local origin.

Adding two vectors is equivalent to combining two vectors to make a sum vector. The sum vector is calculated by adding the two vectors’ number together in the same order. Using the example from above, adding the current position vector and the speed vector will result in a sum vector that represents the new position.

## Vector Subtraction

Subtracting two vectors will result in a difference or offset vector. This represents the vector that connects the two endpoints. This is incredibly useful in games that need to know the distance of two objects or the direction required to move from one object to another. Here’s an example of an offset vector to determine the distance and direction of two players.

#### Order of Operands

Unlike vector addition, the order of operands will change the result of the vector subtraction. The first operand will be the end point of the offset vector while the second operand is the start of the offset vector. Switching the operands will reverse the offset vector’s direction.

## Normalizing a Vector

In some cases, it is useful to keep the direction of a vector but have the length of the vector equal to 1. This is known as normalizing a vector or turning a vector into a unit vector. One use case is to normalize the offset vector of two players to get a speed unit vector for the first player to approach the second player.

## Scaling a Vector

A vector can be multiplied by a single number, which will multiply each number in the vector independently. By normalizing a vector and then multiplying it with a number, any vector can be modified to a desired length. For example, to move one player to another player at a certain speed, the following can be done:

• Subtract the player position vectors to get an offset vector.
• Normalize the offset vector so the length is 1.
• Multiply the normalized vector by the desired speed value.
• The multiplication result is the desired speed vector.