How to toggle a Key Press

0 votes
asked Sep 1, 2014 by vladan899

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

3 Answers

0 votes
answered Sep 1, 2014 by monacraft

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.

0 votes
answered Sep 2, 2014 by folkol

Instead of "Shoot Bullets", flip the value of a boolean variable. And use that variable as the indicated for whether you should fire some bullets in any given game loop iteration.

Something like this:

public class MyGame : Microsoft.Xna.Framework.Game
{ /* Some other state */ bool isShooting = false; /* Some other methods */ protected override void Update(GameTime gameTime) { /* Some other code */ if(keyState.IsKeyDown(Keys.Space)) { // Flip the boolean value. If it was failse, set it to and vice versa isShooting = !isShooting; true. } if(isShooting) { Shoot.Bullets(); } }
}
0 votes
answered Nov 29, 2018 by mark-randle

I added another short but correct example for you, some of the other answers were pretty much there, but had some errors in them.

 KeyboardState kbState; bool isShooting; protected override void Update(GameTime gameTime) { KeyboardState lastkbState = kbState; kbState = Keyboard.GetState(); if (kbState.IsKeyDown(Keys.Space) && lastkbState.IsKeyUp(Keys.Space)) { isShooting = !isShooting; } if (isShooting) { Shoot.Bullets(); } }

Your other answer I don't have the reptuation to add a comment on doesn't work because you made the previous and the current keyboard state properties equal the same thing.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...