Game physics
Give objects weight and momentum. Velocity, acceleration, gravity, friction and bouncing, with a fixed time step that behaves the same on every computer.
On this page
What you'll learn
- Position, velocity and acceleration with
pygame.Vector2 - Gravity, jumping and terminal velocity
- Friction and bouncing
- Collisions between moving balls
- Fixed time steps for stable simulations
Prerequisites: The game loop and collision detection.
Position, velocity, acceleration#
Most game physics is these three lines, run every frame:
vel += acc * dt # acceleration changes velocity
pos += vel * dt # velocity changes positionpos is where the object is, vel is how fast and in which direction it moves (pixels per second), and acc is how quickly the velocity changes (pixels per second squared). pygame.Vector2 lets you write this for x and y at once. Gravity is just a constant downward acceleration, for example Vector2(0, 900).
Jumping#
A jump sets an upward velocity, and gravity pulls it back down:
if jump_pressed and on_ground:
vel.y = -560 # negative y is up in Pygame
vel.y = min(vel.y + GRAVITY * dt, 900) # cap the fall speed ("terminal velocity")The peak height is jump_speed² / (2 × gravity), so with 560 and 1400 the jump rises 112 pixels. Tweak those two numbers until the jump feels right. Many games use stronger gravity while falling than while rising, which makes jumps feel snappier. The platformer also lets the player cut a jump short by releasing the key.
Friction and drag#
Friction slows things down. A simple, frame-rate-independent way is to scale the velocity by a factor per second:
vel.x *= 0.02 ** dt # keeps 2% of the speed after one secondOn a slippery surface use a factor closer to 1. For ground contact you can also apply friction only when touching the floor, as in the example below.
Bouncing#
When a ball hits a wall, flip the velocity component perpendicular to the wall and multiply by a coefficient of restitution between 0 (no bounce) and 1 (perfect bounce). Also move the ball back to the wall's surface, otherwise it can stick and vibrate inside the wall.
Complete example: bouncing balls#
"""Velocity, acceleration, gravity, friction and bouncing with a fixed time step."""
import random
import pygame
WIDTH, HEIGHT = 640, 480
GRAVITY = pygame.Vector2(0, 900) # pixels / second^2
STEP = 1 / 120 # physics runs at 120 Hz whatever the frame rate
RESTITUTION = 0.75 # how much speed survives a bounce (0..1)
FRICTION = 0.98 # ground friction applied each step
class Ball:
def __init__(self, pos, vel, radius, color):
self.pos = pygame.Vector2(pos)
self.vel = pygame.Vector2(vel)
self.radius = radius
self.color = color
def step(self, dt):
self.vel += GRAVITY * dt # acceleration changes velocity
self.pos += self.vel * dt # velocity changes position
if self.pos.y > HEIGHT - self.radius: # floor
self.pos.y = HEIGHT - self.radius
self.vel.y = -self.vel.y * RESTITUTION
self.vel.x *= FRICTION
if abs(self.vel.y) < 30:
self.vel.y = 0
for wall_x, sign in ((self.radius, 1), (WIDTH - self.radius, -1)):
if (self.pos.x - wall_x) * sign < 0:
self.pos.x = wall_x
self.vel.x = -self.vel.x * RESTITUTION
def collide(a, b):
"""Push two overlapping balls apart and exchange momentum along the contact normal."""
delta = b.pos - a.pos
dist = delta.length()
if dist == 0 or dist >= a.radius + b.radius:
return
normal = delta / dist
overlap = a.radius + b.radius - dist
a.pos -= normal * overlap / 2
b.pos += normal * overlap / 2
rel = (b.vel - a.vel).dot(normal)
if rel < 0: # only if they are moving towards each other
impulse = -(1 + RESTITUTION) * rel / 2 # equal masses
a.vel -= normal * impulse
b.vel += normal * impulse
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 24)
rng = random.Random(3)
balls = [Ball((rng.randint(50, 590), rng.randint(40, 200)), (rng.uniform(-200, 200), 0), rng.randint(14, 30),
rng.choice([(91, 147, 230), (244, 197, 49), (232, 93, 82), (110, 200, 120)])) for _ in range(10)]
accumulator = 0.0
running = True
while running:
frame_time = min(clock.tick(60) / 1000, 0.25)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
balls.append(Ball(event.pos, (rng.uniform(-150, 150), -300), 18, (157, 194, 255)))
accumulator += frame_time
while accumulator >= STEP: # fixed time step: same result on any PC
for b in balls:
b.step(STEP)
for i, a in enumerate(balls):
for b in balls[i + 1:]:
collide(a, b)
accumulator -= STEP
screen.fill((20, 26, 46))
for b in balls:
pygame.draw.circle(screen, b.color, b.pos, b.radius)
screen.blit(font.render(f"{len(balls)} balls - click to add one", True, (230, 236, 247)), (16, 16))
pygame.display.flip()
pygame.quit()
The ball-to-ball collision pushes overlapping balls apart along the line between their centres (the normal), then exchanges velocity along that line. Because all balls have the same mass, each receives half of the impulse. The if rel < 0 check skips balls that are already separating, which prevents them sticking together.
Fixed time step#
Physics with a variable dt gives slightly different results at different frame rates, and a long frame can let objects pass through each other. This example uses an accumulator: each frame adds the elapsed time, then the simulation runs in exact 1/120-second steps until the accumulator is used up. Rendering stays at the monitor's pace while physics stays deterministic. The min(..., 0.25) cap stops the simulation from trying to catch up after a long pause, a problem known as the "spiral of death".
When to use a physics library#
Hand-written physics is ideal for platformers and arcade games where you want precise control. For stacking boxes, ragdolls, joints or many interacting bodies, a dedicated engine such as pymunk (a Python wrapper for the Chipmunk2D engine) works well alongside Pygame for drawing.
Common mistakes#
- Moving in pixels per frame while using
dtelsewhere makes speeds inconsistent. Keep every speed in per-second units. - Storing positions in
Rectloses fractions. KeepVector2positions and copy rounded values into the rect. - Testing
y == flooralmost never succeeds with floats. Test>=and clamp. - Forgetting to separate overlapping objects before reversing velocity leads to objects stuck together.
Practice exercises#
- Add air resistance so balls slowly lose horizontal speed while flying.
- Give balls different masses (bigger radius means heavier) and update the impulse formula with
m1andm2. - Press G to flip gravity upside down.
- Draw a velocity arrow from each ball's centre to visualise its motion.