Vector math
Introduction
This tutorial is a short and practical introduction to linear algebra as itapplies to game development. Linear algebra is the study of vectors and theiruses. Vectors have many applications in both 2D and 3D development and Godotuses them extensively. Developing a good understanding of vector math isessential to becoming a strong game developer.
Note
This tutorial isnot a formal textbook on linear algebra. We willonly be looking at how it is applied to game development. For abroader look at the mathematics, seehttps://www.khanacademy.org/math/linear-algebra
Coordinate systems (2D)
In 2D space, coordinates are defined using a horizontal axis (x
) and avertical axis (y
). A particular position in 2D space is written as a pair ofvalues such as(4,3)
.

Note
If you're new to computer graphics, it might seem odd that thepositivey
axis pointsdownwards instead of upwards, as youprobably learned in math class. However, this is common in mostcomputer graphics applications.
Any position in the 2D plane can be identified by a pair of numbers in this way.However, we can also think of the position(4,3)
as anoffset from the(0,0)
point, ororigin. Draw an arrow pointing from the origin to thepoint:

This is avector. A vector represents a lot of useful information. As wellas telling us that the point is at(4,3)
, we can also think of it as anangleθ
(theta) and a length (or magnitude)m
. In this case, the arrowis aposition vector - it denotes a position in space, relative to theorigin.
A very important point to consider about vectors is that they only representrelative direction and magnitude. There is no concept of a vector'sposition. The following two vectors are identical:

Both vectors represent a point 4 units to the right and 3 units below somestarting point. It does not matter where on the plane you draw the vector, italways represents a relative direction and magnitude.
Vector operations
You can use either method (x and y coordinates or angle and magnitude) to referto a vector, but for convenience, programmers typically use the coordinatenotation. For example, in Godot, the origin is the top-left corner of thescreen, so to place a 2D node namedNode2D
400 pixels to the right and 300pixels down, use the following code:
$Node2D.position=Vector2(400,300)
varnode2D=GetNode<Node2D>("Node2D");node2D.Position=newVector2(400,300);
Godot supports bothVector2 andVector3 for 2D and 3D usage, respectively. The same mathematical rulesdiscussed in this article apply to both types, and wherever we link toVector2
methods in the class reference, you can also check out theirVector3
counterparts.
Member access
The individual components of the vector can be accessed directly by name.
# Create a vector with coordinates (2, 5).vara=Vector2(2,5)# Create a vector and assign x and y manually.varb=Vector2()b.x=3b.y=1
// Create a vector with coordinates (2, 5).vara=newVector2(2,5);// Create a vector and assign x and y manually.varb=newVector2();b.X=3;b.Y=1;
Adding vectors
When adding or subtracting two vectors, the corresponding components are added:
varc=a+b# (2, 5) + (3, 1) = (5, 6)
varc=a+b;// (2, 5) + (3, 1) = (5, 6)
We can also see this visually by adding the second vector at the end ofthe first:

Note that addinga+b
gives the same result asb+a
.
Scalar multiplication
Note
Vectors represent both direction and magnitude. A value representingonly magnitude is called ascalar. Scalars use thefloat type in Godot.
A vector can be multiplied by ascalar:
varc=a*2# (2, 5) * 2 = (4, 10)vard=b/3# (3, 6) / 3 = (1, 2)vare=d*-2# (1, 2) * -2 = (-2, -4)
varc=a*2;// (2, 5) * 2 = (4, 10)vard=b/3;// (3, 6) / 3 = (1, 2)vare=d*-2;// (1, 2) * -2 = (-2, -4)

Note
Multiplying a vector by a positive scalar does not change its direction, onlyits magnitude. Multiplying with a negative scalar results in a vector in theopposite direction. This is how youscale a vector.
Practical applications
Let's look at two common uses for vector addition and subtraction.
Movement
A vector can representany quantity with a magnitude and direction. Typicalexamples are: position, velocity, acceleration, and force. In this image, thespaceship at step 1 has a position vector of(1,3)
and a velocity vector of(2,1)
. The velocity vector represents how far the ship moves each step. Wecan find the position for step 2 by adding the velocity to the current position.

Tip
Velocity measures thechange in position per unit of time. The newposition is found by adding the velocity multiplied by the elapsed time(here assumed to be one unit, e.g. 1 s) to the previous position.
In a typical 2D game scenario, you would have a velocity in pixels persecond, and multiply it by thedelta
parameter (time elapsed sincethe previous frame) from the_process()or_physics_process()callbacks.
Pointing toward a target
In this scenario, you have a tank that wishes to point its turret at a robot.Subtracting the tank's position from the robot's position gives the vectorpointing from the tank to the robot.

Tip
To find a vector pointing fromA
toB
, useB-A
.
Unit vectors
A vector withmagnitude of1
is called aunit vector. They are alsosometimes referred to asdirection vectors ornormals. Unit vectors arehelpful when you need to keep track of a direction.
Normalization
Normalizing a vector means reducing its length to1
while preserving itsdirection. This is done by dividing each of its components by its magnitude.Because this is such a common operation, Godot provides a dedicatednormalized() method for this:
a=a.normalized()
a=a.Normalized();
Warning
Because normalization involves dividing by the vector's length, youcannot normalize a vector of length0
. Attempting to do sowould normally result in an error. In GDScript though, trying tocall thenormalized()
method on a vector of length 0 leaves thevalue untouched and avoids the error for you.
Reflection
A common use of unit vectors is to indicatenormals. Normal vectors are unitvectors aligned perpendicularly to a surface, defining its direction. They arecommonly used for lighting, collisions, and other operations involving surfaces.
For example, imagine we have a moving ball that we want to bounce off a wall orother object:

The surface normal has a value of(0,-1)
because this is a horizontalsurface. When the ball collides, we take its remaining motion (the amount leftover when it hits the surface) and reflect it using the normal. In Godot, thereis abounce() method to handle this.Here is a code example of the above diagram using aCharacterBody2D:
varcollision:KinematicCollision2D=move_and_collide(velocity*delta)ifcollision:varreflect=collision.get_remainder().bounce(collision.get_normal())velocity=velocity.bounce(collision.get_normal())move_and_collide(reflect)
KinematicCollision2Dcollision=MoveAndCollide(_velocity*(float)delta);if(collision!=null){varreflect=collision.GetRemainder().Bounce(collision.GetNormal());_velocity=_velocity.Bounce(collision.GetNormal());MoveAndCollide(reflect);}
Dot product
Thedot product is one of the most important concepts in vector math, but isoften misunderstood. Dot product is an operation on two vectors that returns ascalar. Unlike a vector, which contains both magnitude and direction, ascalar value has only magnitude.
The formula for dot product takes two common forms:

and

The mathematical notation||A|| represents the magnitude of vectorA
, andAx means thex
component of vectorA
.
However, in most cases it is easiest to use the built-indot() method. Note that the order of the two vectors does not matter:
varc=a.dot(b)vard=b.dot(a)# These are equivalent.
floatc=a.Dot(b);floatd=b.Dot(a);// These are equivalent.
The dot product is most useful when used with unit vectors, making the firstformula reduce to justcos(θ)
. This means we can use the dot product to tellus something about the angle between two vectors:

When using unit vectors, the result will always be between-1
(180°) and1
(0°).
Facing
We can use this fact to detect whether an object is facing toward anotherobject. In the diagram below, the playerP
is trying to avoid the zombiesA
andB
. Assuming a zombie's field of view is180°, can they see theplayer?

The green arrowsfA
andfB
areunit vectors representing thezombie's facing direction and the blue semicircle represents its field of view.For zombieA
, we find the direction vectorAP
pointing to the playerusingP-A
and normalize it, however, Godot has a helper method to do thiscalleddirection_to(). If the anglebetween this vector and the facing vector is less than 90°, then the zombie cansee the player.
In code it would look like this:
varAP=A.direction_to(P)ifAP.dot(fA)>0:print("A sees P!")
varAP=A.DirectionTo(P);if(AP.Dot(fA)>0){GD.Print("A sees P!");}
Cross product
Like the dot product, thecross product is an operation on two vectors.However, the result of the cross product is a vector with a direction that isperpendicular to both. Its magnitude depends on their relative angle. If twovectors are parallel, the result of their cross product will be a null vector.


The cross product is calculated like this:
varc=Vector3()c.x=(a.y*b.z)-(a.z*b.y)c.y=(a.z*b.x)-(a.x*b.z)c.z=(a.x*b.y)-(a.y*b.x)
varc=newVector3();c.X=(a.Y*b.Z)-(a.Z*b.Y);c.Y=(a.Z*b.X)-(a.X*b.Z);c.Z=(a.X*b.Y)-(a.Y*b.X);
With Godot, you can use the built-inVector3.cross()method:
varc=a.cross(b)
varc=a.Cross(b);
The cross product is not mathematically defined in 2D. TheVector2.cross() method is a commonly used analog of the 3D crossproduct for 2D vectors.
Note
In the cross product, order matters.a.cross(b)
does not give thesame result asb.cross(a)
. The resulting vectors point inopposite directions.
Calculating normals
One common use of cross products is to find the surface normal of a plane orsurface in 3D space. If we have the triangleABC
we can use vectorsubtraction to find two edgesAB
andAC
. Using the cross product,AB×AC
produces a vector perpendicular to both: the surface normal.
Here is a function to calculate a triangle's normal:
funcget_triangle_normal(a,b,c):# Find the surface normal given 3 vertices.varside1=b-avarside2=c-avarnormal=side1.cross(side2)returnnormal
Vector3GetTriangleNormal(Vector3a,Vector3b,Vector3c){// Find the surface normal given 3 vertices.varside1=b-a;varside2=c-a;varnormal=side1.Cross(side2);returnnormal;}
Pointing to a target
In the dot product section above, we saw how it could be used to find the anglebetween two vectors. However, in 3D, this is not enough information. We alsoneed to know what axis to rotate around. We can find that by calculating thecross product of the current facing direction and the target direction. Theresulting perpendicular vector is the axis of rotation.
More information
For more information on using vector math in Godot, see the following articles: