Search code examples
c++if-statementopenglglut

Variable value not being incremented in glutIdleFunc() in C++


I am trying to continuously increment the variable bulletY once I click on letter "b" on the keyboard until the maximum y value window size to give a shooting effect . However bulletY is only being incremented once.

Here are the initial values of the bool flags and double used:

bool shoot = false;
bool isDone = false;
double bulletX = 8000 ;
double bulletY = -1;
double plusX = 0;
double plusY = 0;

Below is the method used to handle key inputs

void key(unsigned char k, int x, int y)//keyboard function, takes 3 parameters
                                    // k is the key pressed from the keyboard
                                    // x and y are mouse postion when the key was pressed.
{
    if (k == 'b') { //SHOO
        shoot = true;
    }

    glutPostRedisplay();//redisplay to update the screen with the changes
}

Finally this is the Anim function which i created to be passed to the Idle function glutIdleFunc(Anim)

void Anim(){
if (shoot==true) {
        bulletX = plusX;
        bulletY = plusY;
        isDone = true;
    }

            if (isDone&& bulletY<450) {
                bulletY += 1;
                std::cout << "bullet Y is currently at : " << bulletY << "\n";
            }
            else {
                isDone = false;
                shoot = false;
            }
        glutPostRedisplay();
    }

Solution

  • It seems that bulletY is always resetting to 0 in your Anim() function, and then it is incremented by 1, so bulletY is 1 all the time.

    Remove bulletY = plusY (which is 0) and it should increment in every iteration.