使用基本的bullet c++模拟,我似乎无法获得正确的物理行为。我正在尝试从一个从STL文件加载的网格中初始化btRigidBody,为此我使用的是lib assimp。
当使用立方体时,物理行为似乎是有效的,但对于矩形形状则不是。在将网格加载到物理中的方式中,我遗漏了什么?
void SimulationManager::addRigidBodyFromMesh (const BodyInfo& bodyInfo, const aiMesh* mesh) {
btTriangleMesh* trimesh = new btTriangleMesh();
for (int i=0;i<mesh->mNumFaces; ++i) {
const aiFace& face = mesh->mFaces[i];
aiVector3D v0 = mesh->mVertices[face.mIndices[0]];
aiVector3D v1 = mesh->mVertices[face.mIndices[1]];
aiVector3D v2 = mesh->mVertices[face.mIndices[2]];
trimesh->addTriangle(
btVector3(v0.x, v0.y, v0.z),
btVector3(v1.x, v1.y, v1.z),
btVector3(v2.x, v2.y, v2.z));
}
btCollisionShape* colShape = new btConvexTriangleMeshShape(trimesh);
//static, non-moving world environment geometry
//bool useQuantization = true;
//shape = new btBvhTriangleMeshShape(trimesh,useQuantization);
this->_collisionShapes.push_back(colShape);
btTransform transform;
transform.setIdentity();
btScalar mass(1.f);
btVector3 localInertia(0, 0, 0);
colShape->calculateLocalInertia(mass, localInertia);
transform.setOrigin(btVector3(bodyInfo.x, bodyInfo.y, bodyInfo.z));
btDefaultMotionState* motionState = new btDefaultMotionState(transform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, motionState, colShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
body->setAngularVelocity(btVector3(bodyInfo.aX, bodyInfo.aY, bodyInfo.aZ));
this->_pDynamicsWorld->addRigidBody(body);
}然后,我更新模拟并检索刚体变换,如下所示:
void SimulationManager::update(double dt, std::vector<BodyTransform>& transforms){
this->_pDynamicsWorld->stepSimulation(dt, 10);
for (int i = 0; i < this->_pDynamicsWorld->getNumCollisionObjects(); ++i) {
btCollisionObject* obj = this->_pDynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
float invMass = body->getInvMass();
if (invMass > 0) {
btTransform trans;
body->getMotionState()->getWorldTransform(trans);
BodyTransform bodyTransform;
bodyTransform.matrix = new btScalar[16];
trans.getOpenGLMatrix(bodyTransform.matrix);
transforms.push_back(bodyTransform);
}
}
};并按如下方式更新opengl网格:
std::vector<BodyTransform> transforms;
simulationManager.update(0.005, transforms);
for (std::vector<BodyTransform>::iterator it = transforms.begin() ; it != transforms.end(); ++it) {
glPushMatrix();
glMultMatrixf((GLfloat*)it->matrix);
drawModel(bar);
glPopMatrix();
delete [] it->matrix;
}这是我的模拟在立方体中的样子:

但是对于矩形,网格最初放置在地板上,它们垂直稳定,这很奇怪:

我将非常感谢在这个主题上的任何帮助。谢谢!
发布于 2018-03-01 03:16:28
经过一段时间的努力,我发现了问题所在,所以我会回答我自己的问题,以防它对其他人有用: bullet希望网格的重心放在它的原点,如果不是这样,你会得到上面看到的奇怪行为。
https://stackoverflow.com/questions/48965659
复制相似问题