Convert Figma logo to code with AI

erincatto logobox2d

Box2D is a 2D physics engine for games

8,069
1,515
8,069
3

Top Related Projects

Pure C# 3D real time physics simulation library, now with a higher version number.

12,417

Bullet Physics SDK: real-time collision detection and multi-physics simulation for VR, games, visual effects, robotics, machine learning etc.

A fast and lightweight 2D game physics library.

2D physics engine for games

9,980

Simple and Fast Multimedia Library

A multi core friendly rigid body physics and collision detection library. Written in C++. Suitable for games and VR applications. Used by Horizon Forbidden West.

Quick Overview

Box2D is a 2D physics engine for games, written in C++. It simulates rigid bodies, joints, and collisions, providing realistic physics interactions for 2D game development. The library is widely used in game development and has been ported to various platforms and programming languages.

Pros

  • Efficient and well-optimized for 2D physics simulations
  • Extensive documentation and community support
  • Cross-platform compatibility
  • Open-source with a permissive license (MIT)

Cons

  • Learning curve can be steep for beginners
  • Limited to 2D physics, not suitable for 3D games
  • May require additional wrappers or bindings for use with some game engines

Code Examples

Creating a world and adding a body:

b2Vec2 gravity(0.0f, -10.0f);
b2World world(gravity);

b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0.0f, -10.0f);
b2Body* groundBody = world.CreateBody(&groundBodyDef);

b2PolygonShape groundBox;
groundBox.SetAsBox(50.0f, 10.0f);
groundBody->CreateFixture(&groundBox, 0.0f);

Creating a dynamic body:

b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(0.0f, 4.0f);
b2Body* body = world.CreateBody(&bodyDef);

b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(1.0f, 1.0f);

b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;

body->CreateFixture(&fixtureDef);

Simulating the world:

float timeStep = 1.0f / 60.0f;
int32 velocityIterations = 6;
int32 positionIterations = 2;

for (int32 i = 0; i < 60; ++i)
{
    world.Step(timeStep, velocityIterations, positionIterations);
    b2Vec2 position = body->GetPosition();
    float angle = body->GetAngle();
    printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
}

Getting Started

  1. Clone the repository:

    git clone https://github.com/erincatto/box2d.git
    
  2. Build the library using CMake:

    cd box2d
    mkdir build
    cd build
    cmake ..
    cmake --build .
    
  3. Include the Box2D headers in your project and link against the built library.

  4. Start using Box2D in your code:

    #include <box2d/box2d.h>
    
    // Create a world
    b2Vec2 gravity(0.0f, -10.0f);
    b2World world(gravity);
    
    // Add bodies and shapes to the world
    // ...
    
    // Simulate the world
    float timeStep = 1.0f / 60.0f;
    world.Step(timeStep, 8, 3);
    

Competitor Comparisons

Pure C# 3D real time physics simulation library, now with a higher version number.

Pros of BEPUphysics2

  • Written in C#, offering better integration with Unity and other .NET environments
  • Designed for high performance, with a focus on multithreading and SIMD optimizations
  • More extensive feature set, including soft body physics and advanced constraint systems

Cons of BEPUphysics2

  • Steeper learning curve due to its more complex architecture
  • Less widespread adoption and community support compared to Box2D
  • Primarily focused on 3D physics, which may be overkill for 2D-only projects

Code Comparison

Box2D (C++):

b2Vec2 gravity(0.0f, -10.0f);
b2World world(gravity);
b2BodyDef groundBodyDef;
b2Body* groundBody = world.CreateBody(&groundBodyDef);

BEPUphysics2 (C#):

var simulation = Simulation.Create(BufferPool, new NarrowPhaseCallbacks(), new PoseIntegratorCallbacks(new Vector3(0, -10, 0)));
var groundShape = new Box(100, 1, 100);
simulation.Statics.Add(new StaticDescription(new Vector3(0, -0.5f, 0), groundShape));

Both libraries offer efficient physics simulations, but BEPUphysics2 provides more advanced features and performance optimizations at the cost of increased complexity. Box2D remains a solid choice for simpler 2D physics needs, while BEPUphysics2 excels in more demanding 3D scenarios and Unity-based projects.

12,417

Bullet Physics SDK: real-time collision detection and multi-physics simulation for VR, games, visual effects, robotics, machine learning etc.

Pros of Bullet3

  • 3D physics simulation capabilities
  • More advanced features like soft body dynamics and fluid simulation
  • Wider industry adoption, especially in game development and robotics

Cons of Bullet3

  • Steeper learning curve due to more complex API
  • Higher computational overhead, potentially impacting performance in simpler scenarios
  • Larger codebase and dependencies, which may increase project size

Code Comparison

Box2D (2D physics):

b2World world(gravity);
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
b2Body* body = world.CreateBody(&bodyDef);

Bullet3 (3D physics):

btDiscreteDynamicsWorld* dynamicsWorld;
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, motionState, shape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
dynamicsWorld->addRigidBody(body);

Box2D focuses on 2D physics with a simpler API, making it easier to use for 2D games and simulations. Bullet3 offers more advanced 3D physics capabilities but requires more setup and has a steeper learning curve. The code comparison illustrates the difference in complexity between creating a basic physics object in each library.

A fast and lightweight 2D game physics library.

Pros of Chipmunk2D

  • Simpler API and easier to integrate into existing projects
  • Better performance for certain types of simulations, especially those involving many small objects
  • More extensive documentation and examples

Cons of Chipmunk2D

  • Less widespread adoption compared to Box2D
  • Fewer advanced features and constraints
  • Limited support for continuous collision detection

Code Comparison

Box2D:

b2World world(gravity);
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
b2Body* body = world.CreateBody(&bodyDef);
b2CircleShape circle;
circle.m_radius = 0.5f;
body->CreateFixture(&circle, 1.0f);

Chipmunk2D:

cpSpace *space = cpSpaceNew();
cpBody *body = cpBodyNew(1.0, cpMomentForCircle(1.0, 0, 0.5, cpvzero));
cpShape *shape = cpCircleShapeNew(body, 0.5, cpvzero);
cpSpaceAddBody(space, body);
cpSpaceAddShape(space, shape);

Both libraries offer similar functionality for 2D physics simulations, but Box2D is more widely used and feature-rich, while Chipmunk2D provides a simpler API and potentially better performance in certain scenarios. The choice between them depends on specific project requirements and developer preferences.

2D physics engine for games

Pros of LiquidFun

  • Includes fluid simulation capabilities, allowing for realistic liquid and soft body physics
  • Optimized for mobile devices and web browsers
  • Provides additional features like particle systems and soft bodies

Cons of LiquidFun

  • Less actively maintained compared to Box2D
  • May have a steeper learning curve due to additional features
  • Potentially higher performance overhead for simpler 2D physics scenarios

Code Comparison

Box2D:

b2World world(gravity);
b2BodyDef bodyDef;
b2Body* body = world.CreateBody(&bodyDef);
b2PolygonShape box;
box.SetAsBox(1.0f, 1.0f);
body->CreateFixture(&box, 1.0f);

LiquidFun:

b2World world(gravity);
b2ParticleSystemDef particleSystemDef;
b2ParticleSystem* particleSystem = world.CreateParticleSystem(&particleSystemDef);
b2ParticleGroupDef pd;
pd.flags = b2_waterParticle;
particleSystem->CreateParticleGroup(pd);

Both libraries share similar base functionality for rigid body physics, but LiquidFun extends Box2D with particle-based fluid simulation capabilities. While Box2D focuses on solid object physics, LiquidFun allows for more complex simulations involving liquids and soft bodies, at the cost of increased complexity and potential performance overhead.

9,980

Simple and Fast Multimedia Library

Pros of SFML

  • Broader scope: SFML is a multimedia library that covers graphics, audio, networking, and window management
  • Higher-level abstraction: Provides easier-to-use interfaces for common game development tasks
  • Cross-platform support: Works on Windows, Linux, macOS, and mobile platforms

Cons of SFML

  • Less specialized: Not focused on physics simulation like Box2D
  • Larger footprint: Includes more features, which may increase project size
  • Steeper learning curve: Due to its broader scope, it may take longer to master all aspects

Code Comparison

SFML (creating a window and drawing a shape):

#include <SFML/Graphics.hpp>

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Window");
    sf::CircleShape shape(100.f);
    shape.setFillColor(sf::Color::Green);
    
    while (window.isOpen()) {
        // Event handling and drawing logic
    }
    return 0;
}

Box2D (creating a world and a body):

#include <box2d/box2d.h>

int main() {
    b2Vec2 gravity(0.0f, -10.0f);
    b2World world(gravity);
    
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(0.0f, 4.0f);
    b2Body* body = world.CreateBody(&bodyDef);
    
    // Simulation loop
    return 0;
}

A multi core friendly rigid body physics and collision detection library. Written in C++. Suitable for games and VR applications. Used by Horizon Forbidden West.

Pros of JoltPhysics

  • Supports 3D physics simulation, while Box2D is limited to 2D
  • Utilizes multi-threading for improved performance
  • Includes more advanced features like soft body dynamics and vehicle simulation

Cons of JoltPhysics

  • Steeper learning curve due to increased complexity
  • Less widespread adoption and community support compared to Box2D
  • Potentially higher computational requirements for simpler 2D scenarios

Code Comparison

Box2D (C++):

b2Vec2 gravity(0.0f, -10.0f);
b2World world(gravity);
b2BodyDef bodyDef;
b2Body* body = world.CreateBody(&bodyDef);
world.Step(timeStep, velocityIterations, positionIterations);

JoltPhysics (C++):

JPH::PhysicsSystem physics_system;
physics_system.Init(max_bodies, num_body_mutexes, max_body_pairs, max_contact_constraints, broad_phase_layer_interface, object_vs_broad_phase_layer_filter, object_vs_object_layer_filter);
JPH::BodyInterface& body_interface = physics_system.GetBodyInterface();
JPH::Body* body = body_interface.CreateBody(body_creation_settings);
physics_system.Update(delta_time, collision_steps, integration_sub_steps);

Both libraries offer robust physics simulation capabilities, with Box2D focusing on 2D and JoltPhysics providing more advanced 3D features. The choice between them depends on the specific requirements of your project, such as dimensionality, performance needs, and desired features.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Box2D Logo

Build Status

Build Status

Box2D

Box2D is a 2D physics engine for games.

Box2D Version 3.0 Release Demo

Features

Collision

  • Continuous collision detection
  • Contact events and sensors
  • Convex polygons, capsules, circles, rounded polygons, segments, and chains
  • Multiple shapes per body
  • Collision filtering
  • Ray casts, shape casts, and overlap queries

Physics

  • Robust Soft Step rigid body solver
  • Continuous physics for fast translations and rotations
  • Island based sleep
  • Revolute, prismatic, distance, mouse joint, weld, and wheel joints
  • Joint limits, motors, springs, and friction
  • Joint and contact forces
  • Body movement events and sleep notification

System

  • Data-oriented design
  • Written in portable C17
  • Extensive multithreading and SIMD

Samples

  • OpenGL with GLFW and enkiTS
  • Graphical user interface with imgui
  • Many samples to demonstrate features and performance

Building

  • Install CMake
  • Ensure CMake is in the user PATH
  • Visual Studio: run build.bat from the command prompt
  • Otherwise: run build.sh from a bash shell
  • Results are in the build sub-folder
  • On Windows you can open box2d.sln

Building for Xcode

  • Install CMake
  • Add Cmake to the path in .zprofile (the default Terminal shell is zsh)
    • export PATH="/Applications/CMake.app/Contents/bin:$PATH"
  • mkdir build
  • cd build
  • cmake -G Xcode ..
  • open box2d.xcodeproj
  • Select the samples scheme
  • Edit the scheme to set a custom working directory to the box2d directory
  • You can now build and run the samples

Compatibility

The Box2D library and samples build and run on Windows, Linux, and Mac.

Box2D should be built on recent versions of clang and gcc. You will need the latest Visual Studio version for C11 atomics to compile (17.8.3+).

AVX2 CPU support is assumed on x64. You can turn this off in the CMake options and use SSE2 instead. There are some compatibility issues with very old CPUs.

Documentation

Community

Contributing

Please do not submit pull requests. Instead, please file an issue for bugs or feature requests. For support, please visit the Discord server.

Giving Feedback

Please file an issue or start a chat on discord.

License

Box2D is developed by Erin Catto and uses the MIT license.

Sponsorship

Support development of Box2D through Github Sponsors

Ports, wrappers, and bindings