Pymunk

7.2.0 · active · verified Thu Apr 16

Pymunk is an easy-to-use pythonic 2D physics library designed for games, demos, and simulations. It is built on top of Munk2D, a fork of the robust Chipmunk2D C physics library. First released in 2007, Pymunk remains actively developed and maintained, with its current version being 7.2.0, and has a regular release cadence with several updates per year.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a basic Pymunk simulation with a falling circle bouncing on a static ground. It covers creating a `Space`, `Body`, `Shape`, applying gravity, and stepping the simulation forward.

import pymunk

# 1. Create a Space (the simulation world)
space = pymunk.Space()
space.gravity = 0, -981  # Set gravity (e.g., 9.81 m/s^2 downwards)

# 2. Create a Body (the physical object)
mass = 1
moment = pymunk.moment_for_circle(mass, 0, 10) # Moment of inertia for a circle
body = pymunk.Body(mass, moment)
body.position = 50, 150 # Initial position of the body

# 3. Create a Shape (for collision detection) and attach to the Body
circle_shape = pymunk.Circle(body, 10) # 10 is radius
circle_shape.friction = 0.7
circle_shape.elasticity = 0.9

# 4. Create a static ground for the ball to land on
ground_shape = pymunk.Segment(space.static_body, (0, 0), (200, 0), 5) # From (0,0) to (200,0) with radius 5
ground_shape.friction = 0.7
ground_shape.elasticity = 0.9
ground_shape.color = (0, 0, 0, 255)

# 5. Add the Body and Shape to the Space
space.add(body, circle_shape, ground_shape)

# 6. Simulate the physics
print(f"Initial position: {body.position}")
for i in range(100): # Run 100 steps of the simulation
    space.step(1 / 60.0) # Advance the simulation by 1/60th of a second
    if i % 10 == 0:
        print(f"Step {i}: Position: {body.position}")

print(f"Final position: {body.position}")

view raw JSON →