Box2D is a 2D physics engine for games

Box2D Logo

Build Status

Build Status

Box2D

Box2D is a 2D physics engine for games.

Contributing

Please do not submit pull requests with new features or core library changes. Instead, please file an issue first for discussion. For bugs, I prefer detailed bug reports over pull requests.

Features

Collision

  • Continuous collision detection
  • Contact callbacks: begin, end, pre-solve, post-solve
  • Convex polygons and circles
  • Multiple shapes per body
  • One-shot contact manifolds
  • Dynamic tree broadphase
  • Efficient pair management
  • Fast broadphase AABB queries
  • Collision groups and categories

Physics

  • Continuous physics with time of impact solver
  • Persistent body-joint-contact graph
  • Island solution and sleep management
  • Contact, friction, and restitution
  • Stable stacking with a linear-time solver
  • Revolute, prismatic, distance, pulley, gear, mouse joint, and other joint types
  • Joint limits, motors, and friction
  • Momentum decoupled position correction
  • Fairly accurate reaction forces/impulses

System

  • Small block and stack allocators
  • Centralized tuning parameters
  • Highly portable C++ with no use of STL containers

Testbed

  • OpenGL with GLFW
  • Graphical user interface with imgui
  • Extensible test framework
  • Support for loading world dumps

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 Box2D - Using vcpkg

You can download and install Box2D using the vcpkg dependency manager:

The Box2D port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Note: vcpkg support is not provided by the Box2D project

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 testbed scheme
  • Edit the scheme to set a custom working directory, make this be in box2d/testbed
  • You can now build and run the testbed

Installing using CMake

You can use the CMake install feature to deploy the library to a central location that can be accessed using:

find_package(box2d REQUIRED)
target_link_libraries(mytarget PRIVATE box2d)

You can build and install the library and docs using this command sequence (requires Doxygen):

mkdir build
cd build
cmake -DBOX2D_BUILD_DOCS=ON ..
cmake --build .
cmake --build . --target INSTALL

On Windows this tries to install in Program Files and thus requires admin privileges. Alternatively you can target another directory using something like this:

mkdir build
cd build
cmake -DBOX2D_BUILD_DOCS=ON -DCMAKE_INSTALL_PREFIX="C:/packages" ..
cmake --build .
cmake --build . --target INSTALL

Documentation

License

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

Sponsorship

Support development of Box2D through Github Sponsors

Comments
  • Major random bug causes the engine to quickly go on a downward spiral until it crashes

    Major random bug causes the engine to quickly go on a downward spiral until it crashes

    I'm using Box2d through the gdx-box2d java library, which makes use of the c code through JNI. I've used it without problems in my other games, serverside as they are multiplayer MMO games, but on my newest game, after a random amount of time (usually 1 or 2 days) it suddendly gets really slow until it crashes.

    The game is this one (you can try it without download)

    After trying to solve it java-side, I decided to start touching the c code, basically adding some printf in world.step and related functions.

    b2World.cpp: https://pastebin.com/d6fn0mLd (I added printfs at the end of step displaying m_profiler times, and at different places in SolveTOI)

    b2BroadPhase.h: https://pastebin.com/WTihivb1 (added prints at updatepairs showing moveCount and pairCount)


    After it crashes, I analyse the log, and this is what I see:

    Everything works right until suddendly it slows down, and the pairCount increases substantially.

    {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{}{K}{E1}{F}{G}{E2} {PR|5.61|1.56|3.11|0.25|0.21|0.16|0.55|1.08} (milliseconds of m_profile.step|collide|solve|solveInit|solveVelocity|solvePosition|solveTOI|broadphase) {94||194}{*} (moveCount||pairCount) {A}{B}{C}{D}{E2} {PR|5.05|0.99|3.60|0.21|0.18|0.20|0.42|1.10} {13||44}{*} {86||115}{*} {A}{B}{C}{D}{E2} {PR|4.71|1.07|2.95|0.19|0.18|0.20|0.40|0.97} {14||46}{*} {87||133}{*} {A}{B}{C}{D}{E2} {PR|5.92|1.17|3.82|0.23|0.24|0.24|0.59|1.31} {110||228}{*} {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{}{K}{E1}{F}{G}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|7.20|1.43|4.75|0.32|0.24|0.27|0.90|2.05} {13||48}{*} {81||115}{*} {A}{B}{C}{D}{E1}{F}{G}{E2} {PR|6.46|1.05|4.34|0.27|0.20|0.25|0.68|1.20} {16||45}{*} {97||123}{*} {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|7.12|1.63|4.48|0.14|0.21|0.15|0.82|1.79} {99||250}{*} {A}{B}{C}{D}{E2} {PR|7.19|1.09|5.29|0.28|0.39|0.23|0.73|1.97} {14||49}{*} {90||104}{*} {A}{B}{C}{D}{E1}{F}{G}{E1}{F}{G}{E2} {PR|5.50|1.55|3.13|0.23|0.16|0.23|0.50|1.02} {96||138}{*} {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|6.18|1.20|4.18|0.25|0.18|0.23|0.73|1.72} {16||48}{*} {95||166}{*} {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|5.97|0.99|4.13|0.19|0.19|0.20|0.54|1.40} (milliseconds of m_profile.step|collide|solve|solveInit|solveVelocity|solvePosition|solveTOI|broadphase) {13||42}{*} {90||24011}{*} (moveCount||pairCount) {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|18446744949882880.00|0.97|88.95|0.16|0.24|2.48|18446744949882880.00|84.54} {11||12}{*} {96||24120}{*} {A}{B}{C}{D}{E2} {PR|247.14|16.28|94.44|0.44|0.27|0.21|136.07|90.47} {7||26}{*} {441||951895}

    ...a few seconds...

    {*} {A}{B}{C}{D}

    ...minutes...

    {E2} {PR|18446744949882880.00|7.51|18446744949882880.00|0.38|0.16|0.13|136043.02|18446744949882880.00}

    ...minutes... at this time I see a lot of STUCK at colliding that come from here:

    ` gameServer.getWorld().getBox2dWorld().QueryAABB(

    				new QueryCallback() {
    
    					@Override
    
    					public boolean reportFixture(Fixture fixture) {
    
    						if(tries.incrementAndGet() > 20){
    
    							System.out.println("STUCK AT COLLIDING");
    
    							return false;
    
    						}`
    

    then

    {*} {A}{B}{C}{D}

    ...minutes...

    {E2} {PR|18446744949882880.00|1133.92|18446744949882880.00|290.91|95.83|69.26|185694.27|18446744949882880.00}

    CRASH Sometimes it crashes showing some error at memmove (or something like that) method, and sometimes it doesn't show anything

    A second before that this were the world stats (normal):

    06-21 08:19:34 - 79 persons - 2400 entities - 1 preStep - 2401 bodies - 30 joints - ##### Physics: 6.83 (4.08/5.67/8.7) - Players: 0.08 (0.04/0.1/0.65) - Entities: 2.2 (1.97/2.84/5.7) - AI: 0.09 (0.07/0.13/0.27) - Data: 14.23 (10.79/14.6/22.03) - TOTAL: 8.74/23.34 #####

    Any kind of help, even about where to continue looking for the cause is welcome. I'm hopeless right now, and the game is stuck as I don't want to continue updating or advertising it because it crashes every 1 or 2 days.

    I've already checked if there were any updates on related code in current box2d master that weren't in box2d version, but there aren't.

    Thanks in advance.

  • CMake enhancements

    CMake enhancements

    First of all, thanks for finally providing CMake as the official build 
    system. It makes stuff a lot easier for me. I made a patch to enhance it. 
    Sorry I didn't break the patch down into smaller chunks, it has to be 
    patched in a single go in order to work properly. 
    
    Modications are as follows (relative to trunk/Box2D/):
    1) Testbed/Tests/VerticalStack.h: include stdio.h so that printf is defined
    2) Testbed/CMakeLists.txt: rename freeglut to glut because that is the 
    actual default name of the library
    3) freeglut/CMakeLists.txt: change freeglut to glut in library output name 
    to match with 2)
    4) CMakeLists.txt: add options for shared/static/examples building
    5) CMakeLists.txt: compile freeglut only if on Windows, use system 
    libraries on Linux (no experience with Mac, sorry)
    6) CMakeLists.txt: install documentation
    7) CMakeLists.txt: add VERSION
    8) Box2D/CMakeLists.txt: add support for shared/static building
    9) Box2D/CMakeLists.txt: respect VERSION
    10) Box2D/CMakeLists.txt: make MSVC stuff optional (only if compiler 
    actually is MSVC)
    11) Box2D/CMakeLists.txt: install libraries and headers
    

    Original issue reported on code.google.com by [email protected] on 1 Feb 2010 at 8:02

    Attachments:

  • Shared library

    Shared library

    This pull request add support for building Box2D as a shared library. It fixes #621. By default, the library is built as a static library, you have to add -DBUILD_SHARED_LIBS=ON to the cmake invocation to build the shared library.

    If you merge #630 at the same time, you will have to uncomment some lines in src/CMakeLists.txt so that the library can work properly once installed. Anyway, merging both should result in conflicts. If you plan to merge both, merge #630 first, and I will make the necessary modifications to this PR so that it can be merged smoothly.

  • Body not slowing down with friction for static body (Bug)

    Body not slowing down with friction for static body (Bug)

    It seems like there's a bug in the following set-up, reproducible by with the default settings and Step(1/60f, 8, 8) (not the test-bed settings):

    b2Vec2 gravity;
    gravity.Set(0.0f, -10.0f);
    m_world = new b2World(gravity);
    b2ChainShape chainShape;
    b2Vec2 vertices[] = {b2Vec2(-5,0), b2Vec2(5,0), b2Vec2(5,5), b2Vec2(4,1), b2Vec2(-4,1), b2Vec2(-5,5)};
    chainShape.CreateLoop(vertices, 6);
    
    b2FixtureDef groundFixtureDef;
    groundFixtureDef.density = 0;
    groundFixtureDef.shape = &chainShape;
    
    b2BodyDef groundBodyDef;
    groundBodyDef.type = b2_staticBody;
    
    b2Body *groundBody = m_world->CreateBody(&groundBodyDef);
    b2Fixture *groundBodyFixture = groundBody->CreateFixture(&groundFixtureDef);
    
    b2CircleShape ballShape;
    ballShape.m_radius = 1;
    
    b2FixtureDef ballFixtureDef;
    ballFixtureDef.restitution = 0.75f;
    ballFixtureDef.density = 1;
    ballFixtureDef.shape = &ballShape;
    
    b2BodyDef ballBodyDef;
    ballBodyDef.type = b2BodyType::b2_dynamicBody;
    ballBodyDef.position = b2Vec2(0, 10);
    
    b2Body *ball = m_world->CreateBody(&ballBodyDef);
    b2Fixture *ballFixture = ball->CreateFixture(&ballFixtureDef);
    ball->ApplyForceToCenter(b2Vec2(-1000, -400), true);
    

    As you'll see the ball at the end is meant to stop and in fact, if you choose the ground to be dynamic body instead of static, the ball will stop, but when it's dynamic and the ball is supposed to stop it will pick up speed. Doesn't seem related to the recent changes with density zero improvement. I was able to repro it even in previous commits to that.

  • Box2D is dead?

    Box2D is dead?

    From the latest commit (as of 1/26/2016): The main Box2D library is open source, but not open contribution. Please do not submit pull requests. Exceptions may be considered for build files and other items that are not part of the main library source. Thank you for your understanding.

    Does this mean Box2D is dead?

  • changes in r186 create problems in b2RevoluteJoints with limits 0,0

    changes in r186 create problems in b2RevoluteJoints with limits 0,0

    What steps will reproduce the problem?
    1. Create a pole made up of rectangles linked by b2Revolute joints with default 
    limits on
    2. Try to bend the pole
    
    What is the expected output? What do you see instead?
    - Expected: pole returns to straight (all joints return to reference angle) 
    after being bent
    - What I see: after large bends, pole returns to original shape ridiculously 
    slowly (like, 10 seconds). 
    
    What version of the product are you using? On what operating system?
    - C++ Box2d 2.2.1 latest
    
    Please provide any additional information below.
    - Have narrowed this down to r186 changes 
    - specifically: in 2.1.2, if I remove the "Handle large detachment" segment 
    from b2RevoluteJoint.cpp, it exactly reproduces the behaviour from 2.2.1
    - I'd suggest that the optimization that involved removing this code from the 
    new version has generated a bug.
    
    

    Original issue reported on code.google.com by [email protected] on 31 May 2013 at 11:13

  • 2.4.1: build fails with BOX2D_BUILD_UNIT_TESTS=ON

    2.4.1: build fails with BOX2D_BUILD_UNIT_TESTS=ON

    [ 33%] Building CXX object unit-test/CMakeFiles/unit_test.dir/hello_world.cpp.o
    cd /home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/x86_64-redhat-linux-gnu/unit-test && /usr/bin/g++ -DB2_SHARED -I/home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/src/../include -O2 -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -fstack-protector-strong -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -fdata-sections -ffunction-sections -flto=auto -flto-partition=none -O2 -g -DNDEBUG -fvisibility=hidden -fvisibility-inlines-hidden -std=c++11 -o CMakeFiles/unit_test.dir/hello_world.cpp.o -c /home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/unit-test/hello_world.cpp
    In file included from /home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/unit-test/hello_world.cpp:25:
    /home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/unit-test/doctest.h:4021:47: error: size of array ‘altStackMem’ is not an integral constant-expression
     4021 |         static char             altStackMem[4 * SIGSTKSZ];
          |                                               ^
    
    • [x] Ask for help on discord and/or reddit
    • [x] Consider providing a dump file using b2World::Dump
  • Shared libraries?

    Shared libraries?

    Hi! I maintain the Fedora package for Box2D. I'm looking at upgrading from 2.3.1 to 2.4.0, but I can't get the new cmake build system to build shared libraries, only static. Is this by design, or have I missed something? Thank you!

  • How to render an object with render scaling? Thus simulating objects smaller, and rendering them thus bigger?

    How to render an object with render scaling? Thus simulating objects smaller, and rendering them thus bigger?

    Hi,

    So I just got Box2D working, now I have another problem: Currently, I simulate a object by supplying it with pixel sizes, so: Image of 64x64 gets drawn, and the size in Box2D will also be set a 64x64(Meters). This renders fine by getting the position and applying it, but now i want to have a 4x4meter object, render as an 64x64 sprite on the screen. The problem is, that I don't know how I would scale it properly. Can someone explain me how I would properly set the positions of the sprite accordingly to the b2Body positions? The only options my graphics renderer provide are these:

    SetPosition(x,y);
    SetScale(x,y);
    SetAngle(A);
    

    So no vertex modifying and such(may it be nescesery). Can someone teach me how I would probably convert the sizes to achieve what I want?

    Thanks!

  • cannot compile in linux

    cannot compile in linux

    even after adding defines for linux in config.h and correcting the path of "glext.h" in "egl_platform.h" i cannot compile this on linux In file included from /home/debajyoti/Downloads/Box2D-master/Box2D/glfw/x11_platform.h:52:0, from /home/debajyoti/Downloads/Box2D-master/Box2D/glfw/internal.h:69, from /home/debajyoti/Downloads/Box2D-master/Box2D/glfw/clipboard.c:27: /home/debajyoti/Downloads/Box2D-master/Box2D/glfw/glx_platform.h:57:3: error: #error "No OpenGL entry point retrieval mechanism was enabled" #error "No OpenGL entry point retrieval mechanism was enabled" ^ make[2]: *** [glfw/CMakeFiles/glfw.dir/clipboard.c.o] Error 1 make[1]: *** [glfw/CMakeFiles/glfw.dir/all] Error 2 make: *** [all] Error 2

  • b2Query doesn't always return a valid fixture

    b2Query doesn't always return a valid fixture

    What steps will reproduce the problem?
    --------------------------------------
    
    I have been unable to generate a test that consistently fails. However, for 
    this reason I tend to think the bug is somewhere in the new broadphase balanced 
    tree. I can usually get b2Query to fail if I have 10+ overlapping bodies, and I 
    query a small bounding box at an overlapping location. This does not always 
    fail, and requires multiple test runs, but it will almost definitely fail 1/5 
    times.
    
    What is the expected output? What do you see instead?
    -----------------------------------------------------
    
    I expect Box2D to always report a valid pointer to 
    b2QueryCallback->ReportFixture(proxy->fixture). Instead, occasionally I get an 
    invalid pointer such as 0xdfdfdfdf.
    
    What version of the product are you using? On what operating system?
    I am using the very latest google code version, however, this seems to have 
    been an issue since I updated the new balanced tree code.
    
    Please provide any additional information below.
    ------------------------------------------------
    
    The attached patch to b2World.cpp fixes this bug, but I consider it a hack 
    workaround. Perhaps it can give more insight. Platforms I have tested this 
    error and solution on include Win32 with the microsoft compiler and G++, and 
    ARM cross-compile with G++. I feel the root cause is deeper than this function, 
    and I am only patching a problem produced by broadphase. I'm coding Box2D every 
    day if you have any questions, I'm available within 12 hours.
    
    
    

    Original issue reported on code.google.com by [email protected] on 29 Aug 2011 at 2:57

    Attachments:

  • Warmstart GJK fails

    Warmstart GJK fails

    Make sure these boxes are checked before submitting your issue - thank you!

    • [ ] Ask for help on discord and/or reddit
    • [ ] Consider providing a dump file using b2World::Dump
  • Read/Write dependencies on constraints in contact solvers impacting out of order processors

    Read/Write dependencies on constraints in contact solvers impacting out of order processors

    The contact solver creates constraints between Object A and Object B. When processing these we read values from A and B, and write results to A/B. However, constraints can be created such that the continuous orders have a shared object with the previous constraints that were just processed.

    On an out of order processor like Apple silicon, this creates a read after write dependency that forces all constraints to be processed serially, even if other constraints related to other objects could be processed in parallel. If we randomize the order of constraints after they are generated (or the order which the contacts are processed when generating the constraints) it reduces the chances of two continuous constraints array elements being processed by a shared object. As a result we could see a performance improvement of more than 25% in several cases.

    We are opening an issue to discuss this topic further per the readme!

  • DrawSegment is not called

    DrawSegment is not called

    I already have created three simple examples in: Qt6, PyQt6, and SDL2. I thought that a problem in Qt6 but it the same for three cases. It looks like a bug. These examples try to print hello in the console from DrawSegment().

    I expect to see hello in the console:

    DebugDrawer.cpp

    #include "DebugDrawer.h"
    #include <iostream>
    
    DebugDrawer::DebugDrawer()
    {
    
    }
    
    void DebugDrawer::DrawSegment(const b2Vec2 &p1, const b2Vec2 &p2, const b2Color &color)
    {
        std::cout << "hello" << std::endl;
    }
    
    void DebugDrawer::DrawSolidPolygon(const b2Vec2 *vertices, int32 vertexCount, const b2Color &color) { }
    void DebugDrawer::DrawPolygon(const b2Vec2 *vertices, int32 vertexCount, const b2Color &color) { }
    void DebugDrawer::DrawPoint(const b2Vec2 &p, float size, const b2Color &color) { }
    void DebugDrawer::DrawCircle(const b2Vec2 &center, float radius, const b2Color &color) { }
    void DebugDrawer::DrawSolidCircle(const b2Vec2 &center, float radius, const b2Vec2 &axis, const b2Color &color) { }
    void DebugDrawer::DrawTransform(const b2Transform &xf) { }
    

    I inherited from the b2Draw and overloaded the methods:

    DebugDrawer.h

    #ifndef DEBUGDRAWER_H
    #define DEBUGDRAWER_H
    
    #include "box2d/b2_draw.h"
    
    class DebugDrawer : public b2Draw
    {
    public:
        DebugDrawer();
    
    private:
        void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
        void DrawPoint (const b2Vec2 &p, float size, const b2Color &color);
        void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
        void DrawCircle(const b2Vec2& center, float radius, const b2Color& color);
        void DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color);
        void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);
        void DrawTransform(const b2Transform& xf);
    };
    
    #endif // DEBUGDRAWER_H
    

    I created an object with the box shape:

        b2PolygonShape shape;
        shape.SetAsBox(50.f / WORLD_SCALE, 50.f / WORLD_SCALE);
    
        b2BodyDef bdef;
        bdef.type = b2_staticBody;
    
        pBody = pWorld->CreateBody(&bdef);
        pBody->CreateFixture(&shape, 2.f);
    

    I set the debug draw in the main.cpp file:

        pDebugDrawer = new DebugDrawer();
        pWorld->SetDebugDraw(pDebugDrawer);
    

    I set flags:

       uint32 flags = 0;
        flags += b2Draw::e_shapeBit;
        flags += b2Draw::e_jointBit;
        flags += b2Draw::e_centerOfMassBit;
        flags += b2Draw::e_aabbBit;
        flags += b2Draw::e_pairBit;
        pDebugDrawer->SetFlags(flags);
    

    I call pWorld.Step() and pWorld->DebugDraw():

            pWorld->Step(0.016f, 8, 3);
            pWorld->DebugDraw();
    

    main.cpp

    #ifdef _WIN32
    #include <windows.h>
    extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
    extern "C" __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001;
    #endif
    
    #define SDL_MAIN_HANDLED
    
    #include <glad/glad.h>
    #include <SDL.h>
    #include <box2d/box2d.h>
    #include <iostream>
    #include "DebugDrawer.h"
    
    const float WORLD_SCALE = 30.f;
    b2World* pWorld;
    DebugDrawer* pDebugDrawer;
    b2Body* pBody;
    
    int main()
    {
        // Initialize the SDL2 library
        if (SDL_Init(SDL_INIT_VIDEO) != 0)
        {
            SDL_Log("Failed to initialize the SDL2 library: %s", SDL_GetError());
            return 1;
        }
    
        // Create a SDL window
        const int WIN_WIDTH = 500;
        const int WIN_HEIGHT = 500;
        SDL_Window* window = SDL_CreateWindow(
            "Empty Window",
            SDL_WINDOWPOS_CENTERED,
            SDL_WINDOWPOS_CENTERED,
            WIN_WIDTH, WIN_HEIGHT,
            SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
    
        // Create a SDL renderer
        SDL_Renderer* renderer = SDL_CreateRenderer(
            window, -1, SDL_RENDERER_ACCELERATED);
        if (!renderer)
        {
            SDL_Log("Failed to create a SDL renderer %s", SDL_GetError());
            return 1;
        }
    
        SDL_GLContext context = SDL_GL_CreateContext(window);
    
        // Initialize the GLAD library
        if (!gladLoadGL())
        {
            SDL_Log("Failed to initialize the GLAD library");
            return 1;
        }
    
        glViewport(0, 0, WIN_WIDTH, WIN_HEIGHT);
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
    
        b2Vec2 gravity(0.f, 9.8f);
        pWorld = new b2World(gravity);
    
        pDebugDrawer = new DebugDrawer();
        pWorld->SetDebugDraw(pDebugDrawer);
    
        uint32 flags = 0;
        flags += b2Draw::e_shapeBit;
        flags += b2Draw::e_jointBit;
        flags += b2Draw::e_centerOfMassBit;
        flags += b2Draw::e_aabbBit;
        flags += b2Draw::e_pairBit;
        pDebugDrawer->SetFlags(flags);
    
        b2PolygonShape shape;
        shape.SetAsBox(50.f / WORLD_SCALE, 50.f / WORLD_SCALE);
    
        b2BodyDef bdef;
        bdef.type = b2_staticBody;
    
        pBody = pWorld->CreateBody(&bdef);
        pBody->CreateFixture(&shape, 2.f);
    
        SDL_Event event;
        bool running = true;
        SDL_PollEvent(&event);
    
        while (running)
        {
            switch (event.type)
            {
            case SDL_QUIT:
                running = false;
                break;
            case SDL_KEYDOWN:
                switch (event.key.keysym.sym)
                {
                case SDLK_ESCAPE:
                    running = false;
                    break;
                }
                break;
            }
    
            glClear(GL_COLOR_BUFFER_BIT);
    
            pWorld->Step(0.016f, 8, 3);
            pWorld->DebugDraw();
    
            SDL_GL_SwapWindow(window);
            SDL_PollEvent(&event);
        }
    
        delete pWorld;
        delete pDebugDrawer;
    
        SDL_GL_DeleteContext(context);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 0;
    }
    
  • Corner Collision

    Corner Collision

    The slop level should not prevent re-entry on corners.

    https://user-images.githubusercontent.com/7284063/175177111-bc7c7fe4-08b6-45b6-86ba-ab66e55c5030.mp4

  • Question about islands

    Question about islands

    When building islands, a graph is created where the vertices are bodies. There is an edge between the bodies if there is a contact or a joint between them. As a result, we get several graphs that are added to the island one by one and island.Solve() is executed for them.

    Question: Can I add graphs not one by one, but all at once for the islands that are used in b2World::Solve? Will the behavior of the bodies change after that?

    Why I think so: As I understand it, only contacts and joints with this body can change the position and speed for it. This can be done only by those bodies that are with him in the same graph. This means that bodies from another graph do not affect it. So nothing should change if I add all the graph at once. I don't worry about additional memoty allocation when expanding the islands.

    Thank you.

Related tags
2D physics engine for games

LiquidFun Version 1.1.0 Welcome to LiquidFun! LiquidFun is a 2D physics engine for games. Go to our landing page to browse our documentation and see s

Jan 5, 2023
Openframework wrapper for box2d
Openframework wrapper for box2d

ofxBox2d Introduction This is a simple wrapper for box2d using Openframeworks. The examples below are still in progressive, but should be stable for t

Dec 21, 2022
CMake wrapper for Box2D, since it uses premake5

Box2D CMake Support This is a wrapper around the C++ library Box2D. The Source code can be found on Github Status LICENSE Linux / macOS Windows Issues

Aug 22, 2022
A fast and lightweight 2D game physics library.
A fast and lightweight 2D game physics library.

NEW IN CHIPMUNK 7 Chipmunk 7 is complete and now includes the ARM NEON optimizations, the autogeometry code, and the mulithreaded solver. The latest p

Dec 30, 2022
C++ library for multi-physics simulation

Project CHRONO Project Chrono represents a community effort aimed at producing a physics-based modelling and simulation infrastructure based on a plat

Jan 6, 2023
High-performance C++ multibody dynamics/physics library for simulating articulated biomechanical and mechanical systems like vehicles, robots, and the human skeleton.
High-performance C++ multibody dynamics/physics library for simulating articulated biomechanical and mechanical systems like vehicles, robots, and the human skeleton.

Simbody Simbody is a high-performance, open-source toolkit for science- and engineering-quality simulation of articulated mechanisms, including biomec

Dec 25, 2022
Real-time multi-physics simulation with an emphasis on medical simulation.
Real-time multi-physics simulation with an emphasis on medical simulation.

Introduction SOFA is an open source framework primarily targeted at real-time simulation, with an emphasis on medical simulation. It is mainly intende

Dec 22, 2022
Natively multithreaded physics for threejs with PhysX.

Three-Physx Natively multithreaded physics for threejs with PhysX and an easy interface. Credit to Milkshake inc, physx-js, three-ammo, three-to-canno

Jun 6, 2022
Box2D is a 2D physics engine for games

Build Status Box2D Box2D is a 2D physics engine for games. Contributing Please do not submit pull requests with new features or core library changes.

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

Bullet Physics SDK This is the official C++ source code repository of the Bullet Physics SDK: real-time collision detection and multi-physics simulati

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

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

Jan 7, 2023
2D physics engine for games

LiquidFun Version 1.1.0 Welcome to LiquidFun! LiquidFun is a 2D physics engine for games. Go to our landing page to browse our documentation and see s

Jan 5, 2023
Bounce is a 3D physics engine for games.

Bounce Welcome! Bounce is a 3D physics engine for games. Features Common Efficient data structures with no use of STL Fast memory allocators Built-in

Aug 3, 2022
Real-time oriented physics engine and library that's currently best suited for 2D games.

PlayRho A way to play with physical behaviors like the conservation of momentum. PlayRho is a real-time oriented physics engine and library that's cur

Nov 25, 2022
Openframework wrapper for box2d
Openframework wrapper for box2d

ofxBox2d Introduction This is a simple wrapper for box2d using Openframeworks. The examples below are still in progressive, but should be stable for t

Dec 21, 2022
CMake wrapper for Box2D, since it uses premake5

Box2D CMake Support This is a wrapper around the C++ library Box2D. The Source code can be found on Github Status LICENSE Linux / macOS Windows Issues

Aug 22, 2022
Defold Engine integration with Yandex.Metrica to track your games on Yandex.Games.
Defold Engine integration with Yandex.Metrica to track your games on Yandex.Games.

Yandex.Metrica for Defold Yandex.Metrica is a free of charge web analytics tool for websites, that's the reason why we can use it for HTML5 games. Yan

Nov 26, 2022
A multi core friendly rigid body physics and collision detection library suitable for games and VR applications.
A multi core friendly rigid body physics and collision detection library suitable for games and VR applications.

Jolt Physics Library A multi core friendly rigid body physics and collision detection library suitable for games and VR applications. A YouTube video

Dec 31, 2022
A multi core friendly rigid body physics and collision detection library suitable for games and VR applications.
A multi core friendly rigid body physics and collision detection library suitable for games and VR applications.

A multi core friendly rigid body physics and collision detection library suitable for games and VR applications.

Jan 4, 2023
This repository is about a school project about games with physics, written in C++.
This repository is about a school project about games with physics, written in C++.

Eight Ball Pool ?? A game about playing physics-based eight ball pool. ?? Table of Contents About Getting Started Usage Built Using About the creators

Sep 3, 2022