使对象消失并出现在 OpenGL 中

Make object disappear and appear in OpenGL

#include <stdio.h> // this library is for standard input and output
#include "glut.h" // this library is for glut the OpenGL Utility Toolkit
#include <math.h>

// left square
void drawShape1(void) {
    glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(82, 250);
    glVertex2f(82, 200);
    glVertex2f(140, 200);
    glVertex2f(140, 250);
    glEnd();
}

// right square
void drawShape2(void) {
    glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);
    glVertex2f(232, 250);
    glVertex2f(232, 200);
    glVertex2f(290, 200);
    glVertex2f(290, 250);
    glEnd();
}

void initRendering() {
    glEnable(GL_DEPTH_TEST);
}

// called when the window is resized
void handleResize(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0f, (float)w, 0.0f, (float)h, -1.0f, 1.0f);
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    drawShape1();
    drawShape2();
    glutSwapBuffers();
    glutPostRedisplay();
}

// the timer code
void update(int value) {
    // add code here

    glutPostRedisplay();
    glutTimerFunc(5, update, 0);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(400, 400);
    glutCreateWindow("Squares");
    initRendering();
    glutDisplayFunc(display);
    glutReshapeFunc(handleResize);
    glutTimerFunc(5, update, 0);
    glutMainLoop();
    return(0);
}

中间有两个方块。一个方块在左边,另一个方块在右边(见下面的截图)。我正在尝试每 5 秒制作一次左方块 disappear/appear。我已经添加了计时器代码,但我正在努力研究如何制作对象 disappear/appear。

预览:

第一个参数的单位是glutTimerFunc毫秒而不是秒。所以 5 秒等于值 5000。

创建一个类型为 bool 的变量 (square1_visible),它表示左方块是否可见:

bool square1_visible = true;

在定时器函数中每5秒改变变量square1_visible的状态update:

void update(int value) {
    glutTimerFunc(5000, update, 0);
    square1_visible = !square1_visible;
}

根据变量的状态绘制左边的正方形square1_visible:

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    if ( square1_visible )
        drawShape1();
    drawShape2();
    glutSwapBuffers();
    glutPostRedisplay();
}