Monday 23 July 2012

Custom motion states - btMotionState - Bullet Physics

Instead of having one main loop where the rendering of world objects are performed, it makes sense to use Bullets motion states.  Instead of updating the position of all your objects with each render loop, you can use bullet to only update objects that have moved!


What do you need to do?


Well you will need to create your own motion state.


Within Xcode create yourself a c++ header.


Rename it to .hpp 
This will allow you to have a mixture of c++ and Objective-C code.


When my class is only going to be small I have written my entire class within the header file, this is no doubt bad practice but for small classes I find it easier to manage.


Remember an Objective-C class cannot inherit a C++ class, but you can write a C++ class with Objective-C code.


So I create my class which inherits btMotionState.


class MyMotionState : public btMotionState {

Now within my class I have the code which updates my cocos3d node.

virtual void setWorldTransform(const btTransform &worldTrans) {
        if(NULL == mVisibleobj)
            return       
        
        btQuaternion rot = worldTrans.getRotation();
        mVisibleobj.quaternion = CC3Vector4Make(rot.getX(), rot.getY(), rot.getZ(), -rot.getW());
       
        btVector3 pos = worldTrans.getOrigin();
        mVisibleobj.location = CC3VectorMake(pos.getX(), pos.getY(), pos.getZ());;
     
    }


It's that simple.

On creation of an instance of this motion state make sure you can set a reference to your CC3Node.

 MyMotionState(const btTransform &initialpos, CC3Node *node) {
        mVisibleobj = node;
        mPos1 = initialpos;
    }

Now use your new motion state instead of the default one.

Duncan.



1 comment: