"""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()