baruj
baruj

Reputation: 43

Can't animate the exact object that I want in openGL & GLUT

When I clicked the right button on the particular object it gets started to animate. However, whether I click on the same object to stop it -the animating one- or any other object which is not animating, the animating object stops. But, I want animating object to be stopped only when I click on it.

How can I fix this problem? Here is my onClick and onTimer functions. Should I use the animating bool in structure? if so, how?

if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {

        for(i=0; i<MAX; i++){
            if(mx >= arr[i].xB + 0 && mx <= arr[i].xB + 130 && my <= arr[i].yB + 17 && my >= arr[i].yB + - 17){
                animation = !animation;
                animationNumber = i;
                printf("TRUE\n");
            }
        }

void onTimer( int v) {

    glutTimerFunc( TIMER_PERIOD, onTimer, 0) ;


    if(animation){
        arr[animationNumber].xB++;
    if(arr[animationNumber].xB >= 640)
        arr[animationNumber].xB -= 1410;
    }

    glutPostRedisplay() ; // display()

}

Upvotes: 1

Views: 214

Answers (1)

Rabbid76
Rabbid76

Reputation: 210889

Use an array bool animation[MAX] instead of the single boolean variable animation and the indexing variable animationNumber.
With this solution each object has its own state which indicates if it is "animating" or stands still.

bool animation[MAX] = {};

Change the corresponding state of the object in the array, when the mouse button is pressed:

if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{
    for (i=0; i<MAX; i++)
    {
        if (mx >= arr[i].xB + 0 && mx <= arr[i].xB + 130 &&
            my <= arr[i].yB + 17 && my >= arr[i].yB + - 17)
        {
            animation[i] = !animation[i];
            printf("TRUE\n");
        }
    }
}

Traverse all the objects in the timer function and update the positions of the objects:

void onTimer( int v) 
{
    glutTimerFunc( TIMER_PERIOD, onTimer, 0) ;

    for (i=0; i<MAX; i++)
    {
       if(animation[i])
       {
           arr[i].xB++;
           if( arr[i].xB >= 640)
               arr[i].xB -= 1410;
       }
    }
    glutPostRedisplay();
}

Upvotes: 1

Related Questions