Switching OpenGL to perspective mode on top of a half rendered orthographic scene?
-
26-09-2019 - |
Question
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);
OTHER TIPS
Well, "just do it"
- set your projection matrix as ortho
- set your modelview for 2D objects
- render your 2D objects
- set your projection matrix as projection
- set your modelview for 3D objects
- render your 3D objects
... and this can go on again an again
- and swap buffers.
If you KNOW the order of your objects as you seem to do, you can also clear the z-buffer between each render.
I agree with previous posts, and I think more general case is like 3D object and 2D gui. Just for re-emphasis. : )
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective( 45.0f, (GLfloat)s_width/(GLfloat)s_height, near, far);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// render 3D object
glUseProgram(modelProgram);
glSetUniformMat(glGetUniformLocation(model.mvp, "mvp"), mvpMat);
glBindVertexArray(model.vao);
glDrawArrays(GL_TRIANGLES, 0, model.size);
glUseProgram(0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// draw GUI
renderGUI();