Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 41 ยท Game Physics and Animation

Vectors, Angles and Trigonometry in Pygame

Use pygame.math.Vector2 for movement, normalized direction, distance, aiming with atan2, rotation, projectiles and circular motion in your games.

Almost every question in a 2D game is about points and directions. Where is the enemy relative to the player? Which way should the bullet fly? How far apart are two objects? Pygame's pygame.math.Vector2 turns these questions into one-line answers, and a bit of trigonometry (sine, cosine and atan2) handles rotation, aiming and orbits.

Everything in this lesson works without a window, so each example is runnable. We use the real pygame.math module, which the in-browser runner can import headlessly.

What a Vector2 is

A Vector2 holds two floats, x and y. It can represent a position (a point) or a direction with a length (a displacement, velocity or force). It supports arithmetic with operators:

Python
from pygame.math import Vector2

a = Vector2(3, 4)
b = Vector2(1, 2)
print(a + b, a - b, a * 2, a / 2)    # component-wise
print(a.length())                    # 5.0, the Pythagorean theorem
print(a.dot(b))                      # 11.0

Instead of writing x1 + x2, y1 + y2 everywhere, you write p1 + p2. Velocity, acceleration and position updates collapse to pos += vel * dt.

Python Vector2 basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Direction: normalize before you multiply

To move an object towards a target at a constant speed, find the direction, make it a unit vector (length 1), then scale by speed and time.

Python
def move_towards(pos, target, speed, dt):
    direction = target - pos
    distance = direction.length()
    if distance == 0:
        return pos
    step = speed * dt
    if step >= distance:               # would overshoot: arrive exactly
        return Vector2(target)
    return pos + direction / distance * step

Calling normalize() on a zero-length vector raises ValueError, so check the length first or use Vector2.normalize_ip guarded by if v: (a zero vector is falsy). The same trick fixes diagonal speed. Holding right and down gives (1, 1), whose length is 1.414, so normalize the input first:

Python
move = Vector2(dx, dy)
if move.length_squared() > 0:
    move.scale_to_length(1)
pos += move * speed * dt

length_squared() avoids a square root and is faster when you only compare lengths.

Python Move towards a target

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Angles with atan2

To point a sprite at the mouse or a bullet at an enemy you need an angle. The function math.atan2(dy, dx) returns the angle of the vector (dx, dy) in radians, correct in all four quadrants. (Plain atan(dy/dx) breaks when dx is 0 or negative.) Vectors expose this as angle_to, and math.degrees converts units.

Python
import math

dx = mouse_x - player_x
dy = mouse_y - player_y
angle = math.degrees(math.atan2(-dy, dx))      # minus: screen y points down
rotated = pygame.transform.rotate(image, angle)
rect = rotated.get_rect(center=player_pos)

Two important details. First, because screen y grows downward, flip the sign of dy to get the counter-clockwise angle that pygame.transform.rotate expects. Second, rotating a surface produces a bigger surface, so re-center it with get_rect(center=...). Rotate the original image each frame, never the rotated one, or quality degrades.

Going the other way, a direction from an angle uses cosine and sine:

Python
vx = speed * math.cos(math.radians(angle))
vy = -speed * math.sin(math.radians(angle))

The v.from_polar((length, angle)) and v.as_polar() methods do this for you.

Python Aim, fire and orbit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first block shows why atan2 is handy: it returns 0, 90, -180 and -45 degrees for the four directions without any case analysis.

Distance, collision radius and lerp

  • Distance a.distance_to(b) replaces sqrt(dx*dx + dy*dy).
  • Circle collision: two circles touch when a.distance_to(b) < ra + rb. Compare squared distances with distance_squared_to in hot loops.
  • Smooth following (a camera chasing a player): cam = cam.lerp(target, 1 - 0.001 ** dt) closes part of the gap every frame.
  • Reflection: v.reflect(normal) bounces a velocity off a surface, with normal pointing away from the wall.
Python
ball.vel = ball.vel.reflect(Vector2(0, -1))    # bounce off a floor

Cheat sheet

flowchart TD
  Q["What do you need?"] --> A["Direction to a target"]
  Q --> B["Constant speed along it"]
  Q --> C["Angle to rotate a sprite"]
  Q --> D["Velocity from an angle"]
  A --> A1["(target - pos)"]
  B --> B1["direction.normalize() * speed * dt"]
  C --> C1["degrees(atan2(-dy, dx))"]
  D --> D1["v.from_polar((speed, angle))"]

Common mistakes

  • Normalizing a zero vector raises an error. Test if v: or length_squared() first.
  • Mixing degrees and radians. math.sin wants radians; pygame.transform.rotate and Vector2.rotate want degrees.
  • Forgetting the y flip and having sprites aim at a mirrored point.
  • Sharing a vector by reference. b = a makes both names point to one object. Use Vector2(a) or a.copy() when you need a separate vector.
  • Rotating the same surface repeatedly. Always rotate the untouched original.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why normalize an input direction before multiplying by speed?

    A (1, 1) vector has length about 1.41, which makes diagonal movement 41% faster unless it is scaled to length 1.
  2. 2. Which function returns the angle of the vector (dx, dy) correctly in every quadrant?

    atan2 handles dx = 0 and negative dx, and returns radians.
  3. 3. Why is the y component often negated before calling atan2 for a Pygame sprite?

    Mathematical angles assume y points up; the screen has y pointing down.
  4. 4. What does v.lerp(target, 0.5) return?

    lerp is linear interpolation: 0 gives v, 1 gives target, 0.5 the midpoint.

Summary

  • Vector2 stores positions and displacements and supports +, -, * and /.
  • Normalize before scaling by speed so every direction moves at the same rate.
  • atan2(-dy, dx) gives the angle to a target; cos and sin or from_polar turn an angle into a direction.
  • distance_to, lerp and reflect solve following, collision radii and bouncing.
  • Watch for radians versus degrees, the flipped y axis and zero-length vectors.

Next: Sprite Sheet Animation