Learn & Review: Simulating physics in Python

Jan 23, 2026

Simulating physics in Python

audio

Media preview

Transcript

Transcript will appear once available.

summarize_document

Physics Simulation in Pygame and Pymunk

This tutorial demonstrates how to create a physics simulation in Pygame using the Pymunk library. The simulation features physically accurate falling objects (apples) that can be spawned by clicking the mouse.

Core Concepts and Libraries

  • Pymunk: A 2D physics library that calculates physics in a 2D space. It can be used independently for calculations, but requires a visualization library to display the results.
  • Pygame: A library used for visualizing the physics calculations performed by Pymunk. It handles the rendering of objects on the screen.
  • Independence: Pymunk and Pygame are independent. Pymunk's calculations can be visualized with various libraries (e.g., Piglet, Matplotlib, Pygame Arcade), not just Pygame.

Setting Up the Environment

  1. Installation:
    • Install Pygame: pip install Pygame
    • Install Pymunk: pip install PyMonk
  2. Importing Libraries:
    • Import Pygame: import pygame
    • Import Pymunk: import pymunk

Pymunk Simulation Basics

  1. Space:
    • Represents the physics simulation environment or "universe."
    • Created using pymunk.Space().
    • Requires continuous updates to simulate movement.
  2. Gravity:
    • A fundamental physical law applied within the Space.
    • Set using space.gravity = (gravity_x, gravity_y).
    • Values are fictional and adjusted for visual appeal.
  3. Bodies:
    • Represent physical objects within the Space.
    • Static Body: Does not move, but can be interacted with by other bodies. Used for fixed objects like the ground or obstacles.
    • Dynamic Body: Can be moved and influenced by physics (gravity, collisions). Used for falling objects like apples.
    • Kinematic Body: Can be controlled by external code or player input, and can influence other objects. Not used in this tutorial.
    • Created using pymunk.Body(mass, inertia, body_type).
    • mass: How heavy the object is.
    • inertia: How difficult it is to start the object moving.
    • body_type: pymunk.Body.DYNAMIC, pymunk.Body.STATIC, or pymunk.Body.KINEMATIC.
  4. Shapes:
    • Define the collision boundaries of a Body.
    • A Body needs a Shape to collide with other objects.
    • Simplified shapes (like circles) are often used for performance.
    • For apples, a pymunk.Circle is used, defined by the Body and radius.
  5. Adding to Space:
    • Both Body and Shape must be added to the Space to be part of the simulation: space.add(body, shape).
  6. Updating the Simulation:
    • The simulation needs to be stepped forward in time.
    • This is done using space.step(dt), where dt is the time delta (e.g., 1/50 or 0.02).
    • This update should happen within the main Pygame game loop.

Pygame Visualization

  1. Basic Pygame Setup:
    • Initialize Pygame: pygame.init()
    • Create a display surface: screen = pygame.display.set_mode((width, height))
    • Game loop: while running:
  2. Drawing Objects:
    • Pymunk objects (bodies and shapes) are not directly visible.
    • You need to retrieve their positions from Pymunk and draw corresponding Pygame objects.
    • For Circles (Apples):
      • Get the body's position: apple.body.position.
      • Convert float coordinates to integers for Pygame drawing.
      • Draw a circle using pygame.draw.circle(screen, color, (int(pos_x), int(pos_y)), radius).
    • For Images (Apples):
      • Load the image: apple_surface = pygame.image.load("apple_red.png").
      • Get the image's rectangle: apple_rect = apple_surface.get_rect().
      • Set the rectangle's center to the body's position: apple_rect.center = (int(pos_x), int(pos_y)).
      • Blit the image onto the screen: screen.blit(apple_surface, apple_rect).
  3. Drawing Static Objects (Dots):
    • Similar to drawing apples, but using a static body and a smaller radius.
    • A separate function draw_static_balls is used.

Creating the Simulation

  1. create_apple(space, position) Function:
    • Creates a dynamic pymunk.Body.
    • Creates a pymunk.Circle shape for collision.
    • Adds the body and shape to the space.
    • Returns the shape (or body) for visualization.
  2. static_ball(space, position) Function:
    • Creates a static pymunk.Body.
    • Creates a pymunk.Circle shape.
    • Adds the body and shape to the space.
    • Returns the shape (or body).
  3. Game Loop Logic:
    • Initialization:
      • Create the pymunk.Space and set gravity.
      • Create lists to hold dynamic objects (e.g., apples) and static objects (e.g., balls).
      • Add initial static objects (dots) to the balls list.
    • Event Handling:
      • Check for pygame.QUIT event to close the window.
      • Check for pygame.MOUSEBUTTONDOWN event. If detected, call create_apple with the mouse click position (event.pos) and add the returned shape to the apples list.
    • Physics Update:
      • Call space.step(dt) to advance the physics simulation.
    • Drawing:
      • Clear the screen: screen.fill(background_color).
      • Iterate through the apples list and draw each apple (either as a circle or an image) at its current Pymunk position.
      • Iterate through the balls list and draw each static ball.
      • Update the display: pygame.display.flip().

Key Adjustments and Refinements

  • Apple Shape Radius: The radius of the pymunk.Circle used for collision detection needs to be adjusted to fit the visual representation of the apple, minimizing gaps.
  • Gravity and Wind: The space.gravity vector can be adjusted to simulate wind (horizontal component) or stronger/weaker gravity (vertical component).
  • Object Colors: Colors for Pygame drawing can be customized.
  • Image Integration: Replacing simple circle drawings with loaded images enhances the visual appeal.
  • Positioning: Allowing objects to be spawned at specific positions (mouse click, predefined coordinates) makes the simulation interactive.

Ask Sia for quick explanations, examples, and study support.

Let's Get in Touch

AskSia on InstagramAskSia on TikTokAskSia on DiscordAskSia on FacebookAskSia on LinkedInAskSia on Reddit