Search code examples
c++xbox

Algorithm to toggle a variable but the input is continuous


I am making a program that reads input from an xbox controller and I have some boolean variables in the code that need to be toggled. I have this template for my function.

void toggle(bool condition, bool &variable) // Used to toggle variables
{
}

The condition parameter will be a button on the controller (ex. buttonA) and the variable parameter is a reference to the variable that needs to be toggled (ex. crouching)

The problem is that since the controller input is read constantly, a player cannot press and release the button fast enough that it is not read more than once, which causes the variable I am trying to toggle to just rapidly switch back and forth. The behavior I want is that when A is pressed, the value of crouching changes to the opposite of what it is (crouching = !crouching) but I only want it to be run once when the button is pressed and wait for it to be released before the function can be called again. I have tried but I cannot figure out an algorithm to do this. Any help is appreciated!


Solution

  • This is a common problem with RAW input. That is why there are various types of events and their handlers OS provides. An example is WM_KEYDOWN here.
    If raw input is the only option, you can have an intermediate filter, the result of which can be used to actually toggle the variable in your case.

    for example, if r,P represents released and pressed states of button, a sequence like rrrrrrrrrrrrrrPPPPrrrrrrrrrrrPPrrrrrrrrrrrr would mean you need to toggle it when r -> P transition happens. may be you can have an array with as small as 2 elements and you do it like this sample[1]=sample[0]; sample[0]=control.state; if(sample[0]=='r' && sample[1]='P') then toogle(variable)

    Also, you might try out with a bigger array to avoid any spurious noise, basically adopting a threshold based on minimum human key press duration and unput sampling rate.