Vector math

Introduction

This tutorial is a short and practical introduction to linear algebra asit applies to game development. Linear algebra is the study of vectors andtheir uses. Vectors have many applications in both 2D and 3D developmentand Godot uses them extensively. Developing a good understanding of vectormath is essential to becoming a strong game developer.

Note

This tutorial isnot a formal textbook on linear algebra. Wewill only be looking at how it is applied to game development.For a broader 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) anda vertical axis (y). A particular position in 2D space is writtenas a pair of values such as(4,3).

../../_images/vector_axis1.png

Note

If you're new to computer graphics, it might seem odd that thepositivey axis pointsdownwards instead of upwards,as you probably learned in math class. However, this is commonin most computer graphics applications.

Any position in the 2D plane can be identified by a pair of numbers in thisway. However, we can also think of the position(4,3) as anoffsetfrom the(0,0) point, ororigin. Draw an arrow pointing fromthe origin to the point:

../../_images/vector_xy1.png

This is avector. A vector represents a lot of useful information. Aswell as telling us that the point is at(4,3), we can also think ofit as an angleθ and a length (or magnitude)m. In this case, thearrow is aposition vector - it denotes a position in space, relativeto the origin.

A very important point to consider about vectors is that they onlyrepresentrelative direction and magnitude. There is no concept ofa vector's position. The following two vectors are identical:

../../_images/vector_xy2.png

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,it always represents a relative direction and magnitude.

Vector operations

You can use either method (x and y coordinates or angle and magnitude) torefer to a vector, but for convenience, programmers typically use thecoordinate notation. For example, in Godot, the origin is the top-leftcorner of the screen, so to place a 2D node namedNode2D 400 pixels to the right and300 pixels down, use the following code:

$Node2D.position=Vector2(400,300)

Godot supports bothVector2 andVector3 for 2D and 3D usage, respectively. The samemathematical rules discussed in this article apply to both types.

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 manuallyvarb=Vector2()b.x=3b.y=1

Adding vectors

When adding or subtracting two vectors, the corresponding components are added:

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:

../../_images/vector_add1.png

Note that addinga+b gives the same result asb+a.

Scalar multiplication

Note

Vectors represent both direction and magnitude. A valuerepresenting only magnitude is called ascalar.

A vector can be multiplied by ascalar:

varc=a*2# (2, 5) * 2 = (4, 10)vard=b/3# (3, 6) / 3 = (1, 2)
../../_images/vector_mult1.png

Note

Multiplying a vector by a scalar does not change its direction,only its magnitude. 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. Typical examples are: position, velocity, acceleration, and force. Inthis image, the spaceship at step 1 has a position vector of(1,3) anda velocity vector of(2,1). The velocity vector represents how far theship moves each step. We can find the position for step 2 by addingthe velocity to the current position.

../../_images/vector_movement1.png

Tip

Velocity measures thechange in position per unit of time. Thenew position is found by adding velocity to the previous position.

Pointing toward a target

In this scenario, you have a tank that wishes to point its turret at arobot. Subtracting the tank's position from the robot's position gives thevector pointing from the tank to the robot.

../../_images/vector_subtract2.png

Tip

To find a vector pointing fromA toB useB-A.

Unit vectors

A vector withmagnitude of1 is called aunit vector. They arealso sometimes referred to asdirection vectors ornormals. Unitvectors are helpful when you need to keep track of a direction.

Normalization

Normalizing a vector means reducing its length to1 whilepreserving its direction. This is done by dividing each of its componentsby its magnitude. Because this is such a common operation,Vector2 andVector3 provide a method for normalizing:

a=a.normalized()

Warning

Because normalization involves dividing by the vector's length,you cannot normalize a vector of length0. Attempting todo so will result in an error.

Reflection

A common use of unit vectors is to indicatenormals. Normalvectors are unit vectors aligned perpendicularly to a surface, definingits direction. They are commonly used for lighting, collisions, and otheroperations involving surfaces.

For example, imagine we have a moving ball that we want to bounce off awall or other object:

../../_images/vector_reflect1.png

The surface normal has a value of(0,-1) because this is a horizontalsurface. When the ball collides, we take its remaining motion (the amountleft over when it hits the surface) and reflect it using the normal. InGodot, theVector2 class has abounce() methodto handle this. Here is a GDScript example of the diagram above using aKinematicBody2D:

# object "collision" contains information about the collisionvarcollision=move_and_collide(velocity*delta)ifcollision:varreflect=collision.remainder.bounce(collision.normal)velocity=velocity.bounce(collision.normal)move_and_collide(reflect)

Dot product

Thedot product is one of the most important concepts in vector math,but is often misunderstood. Dot product is an operation on two vectors thatreturns ascalar. Unlike a vector, which contains both magnitude anddirection, a scalar value has only magnitude.

The formula for dot product takes two common forms:

../../_images/vector_dot1.png

and

../../_images/vector_dot2.png

However, in most cases it is easiest to use the built-in method. Note thatthe order of the two vectors does not matter:

varc=a.dot(b)vard=b.dot(a)# These are equivalent.

The dot product is most useful when used with unit vectors, making thefirst formula reduce to justcosθ. This means we can use the dotproduct to tell us something about the angle between two vectors:

../../_images/vector_dot3.png

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 thezombiesA andB. Assuming a zombie's field of view is180°, can they see the player?

../../_images/vector_facing2.png

The green arrowsfA andfB areunit vectors representing thezombies' facing directions and the blue semicircle represents its field ofview. For zombieA, we find the direction vectorAP pointing tothe player usingP-A and normalize it, however, Godot has a helpermethod to do this calleddirection_to. If the angle between thisvector and the facing vector is less than 90°, then the zombie can seethe player.

In code it would look like this:

varAP=A.direction_to(P)ifAP.dot(fA)>0: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 directionthat is perpendicular to both. Its magnitude depends on their relative angle.If two vectors are parallel, the result of their cross product will be a null vector.

../../_images/vector_cross1.png../../_images/vector_cross2.png

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)

With Godot, you can use the built-in method:

varc=a.cross(b)

Note

In the cross product, order matters.a.cross(b) does notgive the same result asb.cross(a). The resulting vectorspoint inopposite directions.

Calculating normals

One common use of cross products is to find the surface normal of a planeor surface in 3D space. If we have the triangleABC we can use vectorsubtraction to find two edgesAB andAC. Using the cross product,ABxAC 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 verticesvarside1=b-avarside2=c-avarnormal=side1.cross(side2)returnnormal

Pointing to a target

In the dot product section above, we saw how it could be used to find theangle between two vectors. However, in 3D, this is not enough information.We also need to know what axis to rotate around. We can find that bycalculating the cross product of the current facing direction and thetarget direction. The resulting perpendicular vector is the axis ofrotation.

More information

For more information on using vector math in Godot, see the following articles: