Физика пули с OpenGL - PullRequest
       27

Физика пули с OpenGL

0 голосов
/ 06 января 2012

У меня возникла проблема с внедрением физики пуль в мою игру opengl. Дело в том, что он не хочет постоянно обновлять мои значения translatef, но только в конце. Код для маркера выглядит следующим образом:

void CGL::initPhysics( void ) {
broadphase = new btDbvtBroadphase();
collisionConfiguration = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfiguration);
solver = new btSequentialImpulseConstraintSolver;
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);

dynamicsWorld->setGravity(btVector3(0,-10,0));


ballShape = new btSphereShape(1);
pinShape = new btCylinderShape(btVector3(1,1,1));
pinShape->setMargin(0.04);

fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,10,0)));
btScalar mass = 1;
btVector3 fallInertia(0,0,0);
ballShape->calculateLocalInertia(mass,fallInertia);

btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),1);

btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0));
btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
dynamicsWorld->addRigidBody(groundRigidBody);

btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,ballShape,fallInertia);
btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
dynamicsWorld->addRigidBody(fallRigidBody);

for (int i=0 ; i<300 ; i++) {
    dynamicsWorld->stepSimulation(1/60.f,10);

    btTransform trans;
    fallRigidBody->getMotionState()->getWorldTransform(trans);

    fallY = trans.getOrigin().getY();
}
state_list.remove( STATE_FALL_BALL );
printf("stoped\n");

}

И функция рисования, которая вызывается в начале, выглядит следующим образом:

void CGL::fallingBall( void ) {
glPushMatrix();

float colBall2[4] = { 0.0f, 0.0f, 1.0f, 1.0f };
glMaterialfv( GL_FRONT, GL_AMBIENT, colBall2);

glTranslatef(0.0f,fallY,0.0f);

printf("fallY: %f\n",fallY);

glutSolidSphere(1.0f,20,20);

glPopMatrix();

}

Дело в том, что она показывает правильное значение в printf этой функции, но перевод вызывается только в начале, я имею в виду, что вижу только последнее состояние.

EDIT

Это измененная функция и цикл. Сбор всей информации, которую я предлагаю, теперь должен работать, но это не так. Ничего не рисует.

initPhysics(){
    for (int i=0 ; i<500 ; i++) 
    {
        draw();

    }
    state_list.remove( STATE_FALL_BALL );
    printf("stoped\n");
}

void CGL::draw(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            current_time = getTime();
            since_update = current_time - last_update;
            printf("time: %f\n",since_update);
            if(since_update>timestep)
            {
                dynamicsWorld->stepSimulation(timestep,10);
                last_update = current_time;
            }
            btTransform trans;
            fallRigidBody->getMotionState()->getWorldTransform(trans);

            fallY = trans.getOrigin().getY();
            fallingBall();
            printf("fallY: %f\n",fallY);
glFlush();
    }

И начальные объявления переменных выглядят так:

last_update = 0;
timestep = 100;
current_time = 0;
since_update = 0;

1 Ответ

1 голос
/ 06 января 2012

Это выглядит немного неорганизованно.Я полагаю, что основной ошибкой для исправления непосредственной проблемы, не углубляясь в многопоточность, было бы сделать что-то вроде этого:

//pseudo-code to get the idea
void draw(){
    // clear Buffers and setup matricies
    ....
    //calculate the time that has pased since the last time that the physics have been calculated
    time_t current_time = getCurrentTime();
    time_t since_update = current_time - last_update;

    //if enough time has passed since the last redraw calculate physics
    if(since_update>timestep)
    {
        dynamicsWorld->stepSimulation(timestep,10);
        last_update = current_time;
    }
    btTransform trans;
    fallRigidBody->getMotionState()->getWorldTransform(trans);

    fallY = trans.getOrigin().getY();

    //draw various object
    ....
    fallingBall();
    //swap buffers or flush()
    glSwapBuffers();
}

Если нет явной причины для использования OpenGL напрямую, я бы предложил использовать более высокуюуровень инструментария.Также обычный отказ от ответственности, что вы в настоящее время используете старую версию OpenGL.

...