简体   繁体   中英

Simplest way to set up a 3D OpenGL perspective projection

There have been many tutorials where each suggests using gluPerspective or glFrustum with a combination of other things, yet I've had difficulties setting up the right matrix. What code do I need to set up a 45˚ perspective view looking down the +z axis?

So far I have:

glShadeModel(GL_SMOOTH);
glClearColor(0,0,0,0);
glClearDepth(1);
glDepthFunc(GL_LEQUAL);
glViewport(0,0,width,height);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45,1,0.1,100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

But that doesn't seem to work. All I get is a black screen when I attempt to draw things.

EDIT: Here's the minimal drawing code:

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glColor3ub(255,255,255);
glBegin(GL_TRIANGLE_STRIP);
 glVertex3f(20,20,20);
 glVertex3f(20,30,20);
 glVertex3f(30,20,20);
 glVertex3f(30,30,20);
glEnd();

Things such as points on (1,1,1) and (2,50,23). They do not appear.

Well there's your problem. The default OpenGL camera has the +Z axis pointing towards the camera. And since the camera is at Z=0, any position who's Z position is >0 is behind the camera.

Move your points in front of the camera. They need to at least have a -Z position.

EDIT: Here's the minimal drawing code:

 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glColor3ub(255,255,255); glBegin(GL_TRIANGLE_STRIP); glVertex3f(20,20,20); glVertex3f(20,30,20); glVertex3f(30,20,20); glVertex3f(30,30,20); glEnd(); 

Your vertex coordinates lie way outside the viewing volume. First, OpenGL by default "looks" down the negative Z axis, so your Z coordinates must be -100 < z < -0.1 for your choosen near and far clip plane.

But even if you flipped the sign on the Z coordinate, your vertices still would lie outside the 45° FOV. (20, 0, 20) is 45° from the viewing axis, and (30, 0, 20) even farther. Try centering your vertex coodinates around (0,0,-5) like (+/-1, +/-1, -5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM