Search code examples
copenglglut

Opengl add a new object in each click?


void onClick(int button, int state, int x, int y) {
  if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
    drawHouse(x,y);
}

I have a problem about opengl onclick function. I drawed an object(primitive house) and i want to display it when i click on the mouse. How can i do this?

My teacher gave this command: "Add a new object, defined in the first part, after the user presses mouse left button. Each click adds a new object at the position of click. Maximum 10 objects can be created on the screen. Then, after each click a new object should replace the first object."


Solution

  • One possible soultion would be to store the mouse positions in an array with length of 10. Each click adds a new entry to the array. If the array is full, the entries get overwritten:

    #define MAX_OBJ 10
    
    int pos_x[MAX_OBJ], pos_y[MAX_OBJ];
    int count  = 0;
    int next_i = 0;
    
    void onClick(int button, int state, int x, int y)
    {
        if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
        {
           pos_x[next_i] = x;
           pos_y[next_i] = y;
           next_i ++;
           if ( next_i == MAX_OBJ ) next_i = 0;
           if ( count < MAX_OBJ )   count ++;
        }
    }
    

    In the main loop you can draw the objects to the known positions:

    for( int i = 0; i < MAX_OBJ; ++ i )
        drawHouse( pos_x[i], pos_y[i] );