Code Snippets

From Physics Simulation Wiki

Jump to: navigation, search


Code Snippets

Simple Triangle Meshes

I don't want anything complicated, I just want a simple triangle mesh that stuff can collide with! What's the simplest possible code to “just make a triangle mesh”?

btTriangleMesh *mTriMesh = new btTriangleMesh();

while(!done) {
    // For whatever your source of triangles is
    //   give the three points of each triangle:
    btVector3 v0(x0,y0,z0);
    btVector3 v1(x1,y1,z1);
    btVector3 v2(x2,y2,z2);

    // Then add the triangle to the mesh:

btCollisionShape *mTriMeshShape = new btBvhTriangleMeshShape(mTriMesh,true);

// Now use mTriMeshShape as your collision shape.
// Everything else is like a normal rigid body

I want to constrain an object to two dimensional movement, skipping one of the cardinal axes

The best way of locking the motion in 2D is using btRigidBody::setLinearFactor and btRigidBody::setAngularFactor. This will be available in Bullet 2.75 (and in latest trunk).

btRigidBody::setLinearFactor takes a btVector3 as argument, where its x,y and z correspond to worldspace motion along those axis. Use a 1 to allow motion, and 0 to disallow motion along a certain axis.

The same for btRigidBody::setAngularFactor, where x,y and z corresponds to rotation along those axis.

If you want to limit the motion of objects in the X-Z plane, and only rotation along the Y axis, use:


I want to cap the speed of my spaceship

What's important here is two things: Firstly, doing it in a manner that doesn't go against general physics coding karma. Secondly, doing it in a way that is framerate-independant.

To avoid messing with general physics coding karma, you should make sure you don't accidentally do this while the physics is actually stepping, and while you'd ideally like to avoid setting properties directly on the body, in this particular case you don't have a choice.

To make sure that this is done in a manner that leads to framerate-indepedance, you need to do it *every* time that bullet ticks internally. Just waiting for stepSimulation to return is insufficient since your spaceship might be above the max velocity for multiple internal ticks.

In short, the best way to do this is by setting the velocity of your spaceship in the physics tick callback.

void myTickCallback(btDynamicsWorld *world, btScalar timeStep) {
    // mShipBody is the spaceship's btRigidBody
    btVector3 velocity = mShipBody->getLinearVelocity();
    btScalar speed = velocity.length();
    if(speed > mMaxSpeed) {
        velocity *= mMaxSpeed/speed;

Personal tools