简体   繁体   中英

can't render shape in openGL

I was trying to follow example codes to simply display a rectangle on a black background, but it didn't seem to be displaying. What I did was

    private static void initGL(){
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity(); 
    glOrtho(0,Display.getWidth(),0,Display.getHeight(),-1,1);
    glMatrixMode(GL_MODELVIEW);

    glDisable(GL_DEPTH_TEST); //2D mode

    glColor3f(0.5f, 0.0f, 1.0f); 
    glBegin(GL_QUADS); 
        glVertex2f(-0.75, 0.75);
        glVertex2f(-0.75, -0.75);
        glVertex2f(0.75, -0.75);
        glVertex2f(0.75, 0.75);
    glEnd();
}

It doesn't display anything on the screen except for a black background. Does anyone know what I might have done wrong? I'm using lwjgl in eclipse.

First things first: You only have to run the whole

glMatrixMode(GL_PROJECTION);
glLoadIdentity(); 
glOrtho(0,Display.getWidth(),0,Display.getHeight(),-1,1);
glMatrixMode(GL_MODELVIEW);

thing once during your program, probably shortly after you run Display.create() .

Also, you're tessellating using the wrong vertices. You wrote

glVertex2f(-0.75, 0.75);
glVertex2f(-0.75, -0.75);
glVertex2f(0.75, -0.75);
glVertex2f(0.75, 0.75); 

which means draw a rectangle from (-0.75, -0.75) to (0.75, 0.75) pixels. 到(0.75,0.75) 的矩形。 This is too small to be noticed. My guess is you assumed glVertex2f deals with fractions of the display width. It does not. glVertex2f deals with actual coordinates, it just allows fractional pixels, unlike glVertex2i (this is useful believe it or not, it helps with smoother animations). Something like

glVertex2f(100F, 100F);

places a vertex at (100, 100), and is effectively equivalent to

glVertex2i(100, 100);

Also, remember that negative pixels will be rendered off the screen, because OpenGL's origin of the coordinate system, (0, 0), is in the and behaves like the first quadrant from the coordinate system in math class, not like the traditional computer coordinate system with (0, 0) in the upper left. ,其行为类似于数学类坐标系中的第一个象限,而不是传统的左上角有(0,0)的计算机坐标系。

As for the the black background, LWJGL's Display has a black background by default, so it's recommended to draw a quad with your background color that covers the entire display width and height. One quad won't really affect your performance.

glVertex2f使用与glOrtho相同的尺寸单位,因此,除非您的显示宽度和高度以单位为单位(例如10或更小),否则您可能看不到任何东西!

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