OpenGL黑屏/没有绘制?

Zi0*_*ch0 2 c opengl glut

为什么这段代码会产生黑屏(没有画出来......)?

我正在创建一个Pong克隆但是如果没有让它工作,我就无法继续.

#include <GL/glut.h>

struct Rectangle {
    int x;
    int y;
    int width;
    int height;
};

struct Ball {
    int x;
    int y;
    int radius;
};

typedef struct Rectangle Rectangle;
typedef struct Ball Ball;

Rectangle rOne, rTwo;
Ball ball;

void display(void);
void reshape(int w, int h);
void drawRectangle(Rectangle *r);

int main(int argc, char* argv[]) {

    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
    glutInitWindowSize(800,600);
    glutCreateWindow("Pong");
    gluOrtho2D(0,0,800.0,600.0);

    rOne.x = 100;
    rOne.y = 100;
    rOne.width = 100;
    rOne.height = 50;   

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();

    return 0;

}

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);

    drawRectangle(&rOne);

    glFlush();
    glutSwapBuffers();
}

void reshape(int w, int h) {
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0,0,(GLfloat)w,(GLfloat)h);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void drawRectangle(Rectangle *r) {
    glBegin(GL_QUADS);
        glVertex2i(r->x,r->y);
    glVertex2i(r->x+(r->width-1),r->y);
    glVertex2i(r->x+(r->width-1),r->y+(r->height-1));
    glVertex2i(r->x,r->y+(r->height-1));
    glEnd();
}
Run Code Online (Sandbox Code Playgroud)

gen*_*ult 5

您要求零宽度的正投影:

gluOrtho2D(0,0,(GLfloat)w,(GLfloat)h);
Run Code Online (Sandbox Code Playgroud)

这可能是你的意思:

gluOrtho2D(0,(GLfloat)w,0,(GLfloat)h);
Run Code Online (Sandbox Code Playgroud)

例:

#include <GL/glut.h>

typedef struct {
    int x;
    int y;
    int width;
    int height;
} Rect;

typedef struct {
    int x;
    int y;
    int radius;
} Ball;

Rect rOne, rTwo;
Ball ball;

void display(void);
void reshape(int w, int h);
void drawRectangle(Rect *r);

int main(int argc, char* argv[]) 
{
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(800,600);
    glutCreateWindow("Pong");

    rOne.x = 100;
    rOne.y = 100;
    rOne.width = 100;
    rOne.height = 50;   

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();

    return 0;
}

void display(void) 
{
    glClear(GL_COLOR_BUFFER_BIT);

    drawRectangle(&rOne);

    glFlush();
    glutSwapBuffers();
}

void reshape(int w, int h)
{
    glViewport(0,0,w,h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0,(GLfloat)w,0,(GLfloat)h);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void drawRectangle(Rect *r) 
{
    glBegin(GL_QUADS);
    glVertex2i(r->x,r->y);
    glVertex2i(r->x+(r->width-1),r->y);
    glVertex2i(r->x+(r->width-1),r->y+(r->height-1));
    glVertex2i(r->x,r->y+(r->height-1));
    glEnd();
}
Run Code Online (Sandbox Code Playgroud)