pygame.math

Vector2 and Vector3 make movement, direction, distance and angles readable. Use them for positions, velocities and steering instead of separate x and y variables.

2 min readUpdated
On this page

Overview#

pygame.math.Vector2 (also available as pygame.Vector2) represents a 2D vector: a position, a velocity, or a direction. It supports normal arithmetic and many geometric methods, and can be used anywhere Pygame expects a position, such as pygame.draw.circle(screen, color, pos, 10).

Syntax#

Python
from pygame.math import Vector2

pos = Vector2(100, 200)
vel = Vector2(3, 4)
pos += vel * dt                 # add, subtract, multiply by numbers
pos.x, pos.y                    # components (floats)

Methods#

MethodReturns
length(), length_squared()Magnitude (squared is faster for comparisons).
normalize() / normalize_ip()Unit vector in the same direction (raises ValueError for a zero vector).
scale_to_length(n)Changes the length in place, keeping direction.
distance_to(v), distance_squared_to(v)Distance to another point.
dot(v)Dot product: positive if pointing the same way, 0 if perpendicular.
cross(v)2D cross product (a number): sign tells left or right.
angle_to(v)Angle in degrees from this vector to v.
rotate(deg) / rotate_ip(deg)Rotated copy / in place.
as_polar() / from_polar((r, deg))Convert to and from length and angle.
lerp(v, t)Linear interpolation between vectors, t from 0 to 1.
reflect(normal)Bounce direction off a surface with the given normal.
clamp_magnitude(max)Copy with length limited to max (or a min and max).
move_towards(target, max_distance)Steps towards a target without overshooting.

Module functions pygame.math.clamp(value, low, high) and pygame.math.lerp(a, b, t) work on plain numbers.

Screen coordinates and angles#

Because y grows downward on screen, a positive rotation with Vector2.rotate looks clockwise: Vector2(1, 0).rotate(90) gives (0, 1), which points down. pygame.transform.rotate uses the opposite visual direction, so when you rotate an image to match a velocity, negate the angle:

Python
angle = Vector2(1, 0).angle_to(velocity)            # degrees, screen-clockwise
image = pygame.transform.rotate(original, -angle)  # transform.rotate turns counter-clockwise

Practical example#

math_example.pyDownload
"""pygame.math.Vector2: movement, normalising, angles, rotation, distance and steering."""
import math

import pygame
from pygame.math import Vector2

a = Vector2(3, 4)
print(a.length(), a.normalize(), a * 2, a + Vector2(1, 1))    # 5.0 [0.6, 0.8] [6, 8] [4, 5]
print(Vector2(1, 0).angle_to(Vector2(0, 1)))                    # 90.0 degrees
print(Vector2(10, 0).rotate(90))                                # roughly [0, 10]
print(Vector2(0, 0).distance_to((3, 4)))                        # 5.0
print(Vector2(1, 2).dot(Vector2(3, 4)), Vector2(1, 0).cross(Vector2(0, 1)))  # 11.0 1.0
v = Vector2(0, 0)
v.from_polar((10, 45))                                          # length 10 at 45 degrees
print(round(v.x, 2), round(v.y, 2))

pygame.init()
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
pos, vel = Vector2(320, 180), Vector2(0, 0)
MAX_SPEED, STEER = 260, 600

running = True
while running:
    dt = clock.tick(60) / 1000
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    target = Vector2(pygame.mouse.get_pos())
    desired = target - pos
    if desired.length() > 4:
        desired.scale_to_length(MAX_SPEED)                      # full speed towards the mouse
    else:
        desired = Vector2()
    steering = desired - vel
    if steering.length() > STEER * dt:
        steering.scale_to_length(STEER * dt)                    # limited turning force
    vel += steering
    pos += vel * dt
    heading = math.degrees(math.atan2(vel.y, vel.x)) if vel.length() else 0

    screen.fill((20, 26, 46))
    tip = pos + Vector2(18, 0).rotate(heading)
    left = pos + Vector2(-12, 10).rotate(heading)
    right = pos + Vector2(-12, -10).rotate(heading)
    pygame.draw.polygon(screen, (244, 197, 49), [tip, left, right])
    pygame.draw.circle(screen, (91, 147, 230), target, 5)
    pygame.display.flip()

pygame.quit()

The triangle steers towards the mouse with limited turning force, a classic "seek" behaviour.

Common errors#

  • ValueError: Can't normalize Vector of length zero: check v.length_squared() > 0 before normalising.
  • Diagonal movement is faster: normalise the input direction before multiplying by speed.
  • Mutating shared vectors: a = b shares one object; use a = Vector2(b) or b.copy() for an independent copy.
  • Vectors in Rects: assigning a Vector2 to rect.center rounds to integers; keep the precise position in the vector.

Official documentation#

↑ ↓ to moveEnter to openEsc to close