Search code examples
c++openglsfmlglm-mathbulletphysics

How would i set up collision using the Bullet Physics Library?


hey im having a bit of a "delay" in setting up some collision in my opengl/sfml game. its not much of an error, just asking for some help. Im using Bullet Physics(this is the API reference) and i have been looking at the different functions and classes. then i noticed that there are demos included in the lbrary, so while looking them over i dont completely understand them..

the main library that they recommend me use is CollisionInterfaceDemo since i have already used GLM for models in opengl, and sfml for 2D purposes and the window.

im just wondering if anyone knows how i would be able to implement collision in my game.


Solution

  • Not sure if this is what you're after, but this is my setup code for basic rigid body physics:

    #include "btBulletDynamicsCommon.h"
    
    ...
    
    m_pBroadphase = new btDbvtBroadphase();
    m_pCollisionConfig = new btDefaultCollisionConfiguration();
    m_pCollisionDispatcher = new btCollisionDispatcher(m_pCollisionConfig);
    m_pSolver = new btSequentialImpulseConstraintSolver();
    m_pDynamicsWorld = new btDiscreteDynamicsWorld(m_pCollisionDispatcher, 
                                                   m_pBroadphase, 
                                                   m_pSolver, 
                                                   m_pCollisionConfig);
    

    After that it's just a matter of adding bodies to the world...

    btRigidBody::btRigidBodyConstructionInfo info;
    
    // set physical properties like mass, coefficient of restitution etc
    info.m_mass = 10;
    info.m_restitution = 0.5;
    ...
    
    // Use a motion state to link the physics body with the graphics object.  
    // This is the glue between Bullet and your code, called by bullet to update the 
    // position & orientation of the object
    info.m_motionState = new YourCustomMotionState(...) ; 
    
    btRigidBody* pRigidBody = new btRigidBody(info);
    m_pDynamicsWorld->addRigidBody(pRigidBody);
    

    ...and then updating the world state every frame.

    m_pDynamicsWorld->stepSimulation(deltaTime, m_maxSubSteps);
    

    That will give you a simple physics simulation with rigid bodies that collide and bounce off each other, with Bullet in control of the way bodies move.