Search code examples
xnakeyboardtoggle

How to toggle a Key Press


I have the issue. I have programmed my Shoot em up and i came to dead end when i have to ask so many questions in here

if(key State.IsKeyDown(Keys.Space)) { Shoot Bullets(); }

Problem is when i Hold Space bar it shoots....i do not want to hold Space bar for 30 minutes just to end the level. I wanna make it to toggle. What is best and least coded way to do it. I did spend like 2 days trying to figure this out and i can't...help would be appreciated


Solution

  • As @folkol suggested:

    Include:

    bool Shoot;
    

    And initialize as:

    Shoot = false;
    

    What you check for input

    if(key State.IsKeyDown(Keys.Space)) // Need to flip on key release
        Shoot = !Shoot // Flips the variable
    

    And in your Update() Method:

    if(Shoot)
        Shoot Bullets(); // Shoots
    

    Notice that this will flip the Shoot Variable a lot. You will need to create an oldState value and flip on key release.