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

Pixels move when initialized on their own, but not in loop?

我正在使用 OpenGL/Glut 并尝试制作一个简单的 "rain" 效果。我有一个 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的函数window:

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 init:

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])
    //...
}