用子弹错误的物理行为

时间:2018-02-24 17:32:56

标签: c++ bulletphysics

我似乎无法通过基本的子弹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;
}

以下是我的模拟与立方体的相似之处:

enter image description here

但是对于矩形,网格最初铺设在地板上并且它们垂直稳定,非常奇怪:

enter image description here

我非常感谢有关该主题的任何帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

经过一段时间的努力,我发现问题是什么,所以我会回答我自己的问题,以防它对其他人有用:bullet希望网格的重心位于其原点,如果事实并非如此,你会得到你在上面看到的奇怪行为。