Section 5 was accidently posted out of order. I apologize for that. You can scroll down to the bottom to find section 5.
Section 6. What’s a vector?
Because Vector2s are frequently used to represent both positions and vectors, the first thing to realize is that positions are not vectors. That’s important because in code, they can often look the same and you will often be using them together. Annoying, right?
A vector is a mathmatical and physics concept usually representing a force, velocity, or direction of movement. Specifically, it represents a change in position, but doesn’t hold any data about the position itself. This is surprisingly useful.
Let’s say, I have a Vector2(0,2) and this represents a vector now. Specifically it represents a change in direction that doesn’t change the x direction (to the right) but increases the y direction (upward) by 2. For now, let’s store this vector in a variable called jump.
Vector2 jump = new Vector2(0,2);
Here’s the weird thing about vectors: they have no position information. They can start from anywhere, any position. This “jump” vector just means something is moving two spaces upward. Maybe it’s my player character, maybe it’s a rabbit on the screen somewhere. If we are both jumping, we might have the same vector but be in two completely different positions.
Here’s where this gets really useful: if you add a vector to a position, you get a new position. If my player is at (0,0) and I add “jump” to his position, he’ll have a new position at (0,2).
Let’s take a look at that for a second:
transform.position = transform.position + jump
Notice how there’s no need to construct a new vector2. We are adding two Vectors2 that already exist, and the result is naturally a new Vector2. More specifically, we adding a vector to a position, resulting in a new specific position.
If I instead wrote
transform.position = transform.position - jump
then this is the same as:
transform.position = transform.position - new Vector2(0,2)
or
transform.position = transform.position + new Vector2(-0,-2)
So by simply adding a "negative sign" or "subtracting", I will move downward instead of upward. A negative vector will always result in a vecotor going in the opposite direction.