A 2D physics engine written in Python. This project provides a framework for simulating rigid body dynamics, collision detection, and constraints.
- Rigid Body Dynamics: Simulate the motion of rigid bodies under forces like gravity.
- Collision Detection: Broad-phase and narrow-phase collision detection using AABB and SAT (Separating Axis Theorem).
- Constraints and Joints: Support for distance joints, revolute joints, and more. Recent improvements include better initialization and error handling for joints.
- Visualization: Debugging and visualization tools using Pygame.
-
Clone the repository:
git clone https://github.com/yourusername/physics-engine.git cd physics-engine -
Install the required dependencies:
pip install -r requirements.txt
The project includes several examples to demonstrate the capabilities of the physics engine. To run an example:
python -m examples.simple_fallingHere's a simple example of how to create a custom simulation:
from src.dynamics.world import World
from src.core.body import Body
from src.core.circle import Circle
from src.math.vec2 import Vec2
# Create a world
world = World(gravity=Vec2(0.0, -9.81))
# Create a body with a circular shape
circle = Circle(center=Vec2(0.0, 10.0), radius=1.0)
body = Body(shape=circle, mass=1.0)
# Add the body to the world
world.add_body(body)
# Step the simulation
for _ in range(100):
world.step()src/: Core source code for the physics engine.collision/: Collision detection algorithms.constraints/: Joint and constraint implementations.core/: Core physics classes (e.g., bodies, shapes).debug/: Debugging and visualization tools.dynamics/: Dynamics and world simulation.math/: Mathematical utilities (e.g., vectors, matrices).
examples/: Example simulations.tests/: Unit tests.docs/: Documentation.tools/: Utility tools for benchmarking, visualization, and scene editing.benchmark.py: Measure the performance of the physics engine.export_svg.py: Export simulation scenes as SVG files.scene_editor.py: Create or edit simulation scenes interactively.
The tools/ directory contains utility scripts to assist with development, debugging, and visualization:
To measure the performance of the physics engine, run:
python tools/benchmark.pyThis script simulates varying numbers of bodies and constraints and reports the average time per step.
To export a simulation scene as an SVG file, run:
python tools/export_svg.pyThis script creates a visual representation of the current state of the simulation, which can be useful for documentation or debugging.
To interactively create or edit a simulation scene, run:
python tools/scene_editor.pyThis script provides a simple interface for adding or removing bodies and joints, making it easier to set up complex simulations.
Contributions are welcome! Please open an issue or submit a pull request for any improvements or bug fixes.
This project is licensed under the MIT License. See the LICENSE file for details.