Search code examples
opengl-esorthographicperspectivecamera

Switching OpenGL to perspective mode on top of a half rendered orthographic scene?


We have a mostly 2D game that runs in orthographic mode, but one part shows a 3d model that is rendered in between the other 2D objects. How can I switch to perspective mode, render that model, then switch back to render the other objects in orthographic mode?

Kudos if you can show how it's done in OpenGL ES.


Solution

  • I think this isn't exactly specified question. Are you want more views? Or you want to have 2D background, 3D game objects, 2D gui. If you want this, then:

    • render fullscreen background
    • set viewport to position=obj.pos-obj.size/2, size=obj.size, render object
    • render 2D gui

    Or you want something else?

    EDIT:

    Here's little code:

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,w,0,h,near,far);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(pos.x,...);
    
    DrawQuads();
    
    //if you want to keep your previus matrix
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    gluPerspective(90,width/(float)height,0.001,1000);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    glTranslatef(pos.x,...);
    glRotate(-45.0f,1,0,0);
    glTranslate(0,0,distance from object);
    glRotate(90.0f,1,0,0);
    // or use gluLookAt
    // 0,0,1 - if you want have z as up in view
    // 0,1,0 - for y
    //gluLookAt(pos.x,pos.y,pos.z,cam.x,cam.y,cam.z,0,0,1);
    
    glScale(object.width/model.width,...);
    DrawModel();
    
    // Restore old ortho
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);