c++ - 像素在自行初始化时移动,但不在循环中移动?

标签 c++ list opengl glut

我正在使用 OpenGL/Glut 并尝试制作一个简单的“雨”效果。我有一个关于雨滴的类(class):

class Drop {
    private:
        int speed;
        int posY;
        int posX;
    public:
        Drop() { // constructor
            speed = 5;
            posY = 15;
            posX = (rand() % 500);
        }
        void move() {
            speed += 1;
            posY += speed;
        }
        int getPosY() {
            return posY;
        }
        int getPosX() {
            return posX;
        }
};

Drop 的列表以及将 Drop 添加到列表的函数。

list<Drop> listDrops;
void placeDrop() {
    Drop d = Drop();
    listDrops.push_back(d);
}

重绘 OpenGL 窗口的函数:

void refreshDisplay() {
    if (rand() % 5 == 1) {
        placeDrop();
    }
    glClear(GL_COLOR_BUFFER_BIT);
    glPointSize(5);
    glBegin(GL_POINTS);
    for (Drop a : listDrops) {
        glColor3f(255,255,255); // white
        glVertex2i(a.getPosX(),a.getPosY());
        a.move();
    }
    glEnd();
    glFlush();
    glutSwapBuffers();
}

void repeater(int val) {
    glutPostRedisplay();
    glutTimerFunc(5, repeater, 0);
}

当然还有我的 main 和 Glut 初始化:

int main(int argc, char** argv) {
    srand(time(NULL));
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
    glutInitWindowSize(500, 500);
    glutCreateWindow("Rain");
    gluOrtho2D(0.0, 500.0, 500.0, 0.0);
    glutDisplayFunc(refreshDisplay);
    glutTimerFunc(0, repeater, 0);
    glutMainLoop();
    return 0;
}

所有 Drop 都已正确初始化,我可以通过在创建后输出它们的坐标来确认。但他们根本不动。这就像 Drop::move() 被忽略了。

如果我改为初始化全局 Drop aDrop(只有一个),并在 refreshDisplay() 中删除 listDrops 上的迭代器,并且而不是只绘制 aDrop,它会按预期移动。

最佳答案

您正在对每个 Drop 的拷贝调用 move(),该拷贝仅适用于一次循环迭代

你可以使用

//---------
//        |
//        v
for (Drop &a : listDrops) {
        glColor3f(255,255,255); // white
        glVertex2i(a.getPosX(),a.getPosY());
        a.move();
}

通过引用获取Drop

你之前所做的相当于

for (int i=0; i<listDrops.size();++i) {
    Drop a = listDrops[i]; //a is a copy of the entry
    assert(&a != &listDrops[i])
    //...
}

关于c++ - 像素在自行初始化时移动,但不在循环中移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54707669/

相关文章:

Python:列表索引超出范围/追加列表

c++ - QOpenGLFunctions 缺少重要的 OpenGL 函数

c++ - 使用 OpenCV 和 OpenGL 读取 MP4

c++ - 条件运算符是否应该评估所有参数?

c++ - 当一个人在 Visual Studio 2010 中编译一个 `C` 文件时,它是否被编译为 C++ 文件?

c - 我在 C 中使用指针时遇到问题

c++ - EGL 在第一次 opengl 函数调用时崩溃

python - 停止 VTK 定时器回调

c++ - 将共享指针插入该对象集时,不会调用类重载运算符 '<'

c# - 检查列表中是否已存在相同的对象