Any position in the 2D plane can be identified by a pair of numbers. We can also think of position (4,3) as an offset from (0,0) the origin. An arrow drawn from the origin to our offset is a vector. We can also think of a vector by it's angle and magnitude (length). A key detail is that vectors are always relative and there is no concept of a vector's position. Vectors represent both direction and magnitude. A value representing only magnitude is called a scalar.
godot
You can use either method (x and y coordinates or angle and magnitude) to refer
to a vector, but for convenience, programmers typically use the coordinate
notation. The following refers to a vector 400px
to the right and 300px
down
from the origin (top left):
$Node2D.position = Vector2(400, 300)
Godot supports both Vector2 and Vector3 for 2D and 3D usage.
Member access
The individual components of the vector can be accessed directly by name.
# create a vector with coordinates (2, 5)
var a = Vector2(2, 5)
# create a vector and assign x and y manually
var b = Vector2()
b.x = 3
b.y = 1
Adding vectors
When adding or subtracting two vectors, the corresponding components are added:
var c = a + b # (2, 5) + (3, 1) = (5, 6)
Scalar multiplication
Multiplying a vector by a scalar does not change its direction, only its magnitude. A vector can be multiplied by a scalar:
var c = a * 2 # (2, 5) * 2 = (4, 10)
var d = b / 3 # (3, 6) / 3 = (1, 2)
Movement
A vector can represent any quantity with a magnitude and direction. Typical
examples are: position, velocity, acceleration, and force.
pos2 = pos + vel