matzar
matzar

Reputation: 305

Toggle between three boolean variables in C++

I'm tying to make 3 state toggle for my lighting in OpenGL using C++. So the way I want to do it is when LIGHT0 is enabled LIGHT1 and LIGHT2 are disabled. When LIGHT1 is enabled LIGHT0 and LIGHT2 are disabled etc. I know I can easily toggle between two variables like this:

bool light_0 = true, light_1 = false;
if (key press) {
light_0 = !light_0;
light_1 = !light_1; 
}

And if I use it for three variables then I'll end up switching one light on and switching two lights off.

Upvotes: 0

Views: 1165

Answers (1)

eldo
eldo

Reputation: 1326

Use a state machine.

You need an enum like suggested:

enum Light{
    LIGHT_0, LIGHT_1, LIGHT_2
}

Create an instance of Light to keep track of states.

 Light lightState = new Light();

Whenever you are using your lights you can switch to the current state:

useLight(){
    switch(lightState){
        case LIGHT_0:
            //do whatever you want
            break;
        case LIGHT_1:
            //do whatever you want
            break;
        // and so on, customized for your need
    }
}

Whenever you want to change light just assing the desired light state to lightState.

if(keyPress){
    lightState = LIGHT_1;
}

I hope it's understandable now. (It's not a proper c++ syntax)

Upvotes: 1

Related Questions