Bullet(Cocos2dx)之分析刚体创建与销毁(Primitives)
相关链接:http://bulletphysics.org/mediawiki-1.5.8/index.php/Collision_Shapes
Bullet基本图形简介
Bullet提供的基本图形包括球体、长方体、圆柱体、胶囊体、圆锥体、多球体
当然还有一个Plane,一个无限的平面
1.球体是个很简单的形状:
btSphereShape(btScalarradius)提供一个球体的半径
2.长方体(盒子)
btBoxShape(constbtVector3&BoxHalfExtents)提供盒子的半尺寸(长宽高的一半)
3.圆柱体(类似Boxshape)
btCylinderShape(constbtVector3&halfExtents)提供半尺寸(半径,高度,不知)
默认轴为y轴,btCylinderShapeX(x轴),btCylinderShapeZ(z轴)
4.胶囊体
btCapsuleShape(btScalarradius,btScalarheight)提供半球形半径,圆柱体高度,实际高度为2*radius+height
默认轴为y轴,btCapsuleShapeX(x轴),btCapsuleShapeZ(z轴)
5.圆锥体
btConeShape(btScalarradius,btScalarheight)提供底面半径,高度
默认轴为y轴,btConeShapeX(x轴),btConeShapeZ(z轴)
6.多球体(多个球体组合)
btMultiSphereShape(constbtVector3*positions,constbtScalar*radi,intnumSpheres)
positions每个球体的位置,radi每个球体的半径,球体个数
创建刚体
btCollisionShape*colShape=newbtBoxShape(size*0.5f);//halfSize
因为btBoxShape继承自btCollisionShape
2.设置刚体的其他基本信息
(1).刚体的变换矩阵
(2).刚体的惯性(动态物体才有)
(3).MotionState提供插值,同步活动的物体等
(4).刚体的材质信息
(5).创建刚体
- btTransformstartTransform;//1
- startTransform.setIdentity();
- startTransform.setOrigin(position);
- //rigidbodyisdynamicifandonlyifmassisnonzero,otherwisestatic
- boolisDynamic=(material.mass!=0.f);
- btVector3localInertia(0,0);
- if(isDynamic)
- colShape->calculateLocalInertia(material.mass,localInertia);//2
- //usingmotionstateisrecommended,itprovidesinterpolationcapabilities,andonlysynchronizes'active'objects
- btDefaultMotionState*myMotionState=newbtDefaultMotionState(startTransform);//3
- btRigidBody::btRigidBodyConstructionInforbInfo(material.mass,myMotionState,colShape,localInertia);//4
- rbInfo.m_restitution=material.restitution;
- rbInfo.m_friction=material.friction;
- rbInfo.m_rollingFriction=material.rollingFriction;
- btRigidBody*body=newbtRigidBody(rbInfo);//5
3.将刚体添加到world
_world->addRigidBody(body);
销毁刚体
1.因为刚体继承自btCollisionObject所以从world获取_world->getCollisionObjectArray()
2.如果obj为刚体则要转换为刚体btRigidBody*body=btRigidBody::upcast(obj);
因为刚体有可能包含MoitonState,
3.删除刚体的MotionState,和CollisionShape,(CollisionShape不就是obj吗?查看两者的值是不一样的)
4.从世界移除obj,不是应该移除刚体吗?看源码注释可知
///removeCollisionObjectwillfirstcheckifitisarigidbody,ifsocallremoveRigidBodyotherwisecallbtCollisionWorld::removeCollisionObject
virtualvoid removeCollisionObject(btCollisionObject*collisionObject);
5.释放obj,因为是用new生成的,new实际是Bullet的内存分配方式,重载new
6.释放完毕
- //removethebodiesfromthedynamicsworldanddeletethem
- for(i=_world->getNumCollisionObjects()-1;i>=0;i--)
- {
- btCollisionObject*obj=_world->getCollisionObjectArray()[i];
- btRigidBody*body=btRigidBody::upcast(obj);
- if(body&&body->getMotionState())
- {
- deletebody->getMotionState();
- deletebody->getCollisionShape();
- }
- _world->removeCollisionObject(obj);
- deleteobj;
- }
- 顶
- 0
- 踩
- 0