Search code examples
c++openglvisual-c++glut

Moving 3d Shape in OpenGL


I am writing a program in OpenGL/C++ that creates a number of Spheres and then moves them close to the screen until they are out of sight. I understand how to create the Spheres, but I can't seem to figure out how to move them after they are created. Does anyone know how I can effectively change the move() function so that it increaces z by 1 each time it is called? Or if there is a better way to do this please let me know. Thanks!

 class Sphere {

public:
    double x, y, z;
    void create(double newx, double newy, double r, double g, double b) {
        x = newx;
        y = newy;
        z = -175; // start at back of projection matrix
        glPushMatrix();
        glTranslatef(x, y, z);
        glColor3f(r, g, b);
        glScalef(1.0, 1.0, 1.0);
        glutSolidSphere(1, 50, 50);
        glPopMatrix();
    }
    void move() {
        glPushMatrix();
        //if z is at front, move to start over in the back
        if (z >= 0) {
            z = -176;
            x = rand() % 100;
            y = rand() % 100;
            x = x - 50;
            y = y - 50;
        }
        x = x;
        y = y;
        glPushMatrix();
        z++;
        glTranslatef(x, y, z);
        glPopMatrix();
    }
};

Solution

  • In OpenGL there are no "models created. In fact there are not even "models" in OpenGL. All there is, is a digital canvas, called a framebuffer, and drawing tools offered by OpenGL to draw points, lines and triangles, one at a time. The moment you drew something with OpenGL it already forgot about it.

    Hence the whole notion naming a function "create" is wrong. Instead what you have there is a "draw" function.

    So what you have to do is simple: Redraw the scene, but with your geometry at a different position.