1
votes

I've got a texture that is being displayed on the screen when a key is pressed. The check for this is in the update method based on a boolean help_on. Pressing F1 is if help_on is false, display texture and make help_on true. If help_on true then make it false and here should be the removal of a sprite. Can anyone give me a tip for this? I already know that this is possibly not the way to do it but I got no idea how to do it another way.

2

2 Answers

0
votes

Since I do not know about your game architecture, I will provide a very simple approach:
In your Update method:

kbdState = Keyboard.GetState();
help_on = kbdState.IsKeyDown(Keys.F1);

It's always good to cache KeyboardState since you'll usually want to process more keys than just F1. Then, in your Draw method:

if (help_on)
    spriteBatch.Draw(...); //all your drawing code
0
votes

You need to do two things to make this work as you intend:

First, you need to store the keyboard state across frames, so you can check when the state changes. So: when a key is "up" on one frame, and then "down" on the next, you know that key was "pressed" that frame.

Second, to toggle a variable, just set the new value of that variable to "not" the current value of the variable (set it to its inverse).

See the following code, which could be put in your game class:

bool help_on;
KeyboardState lastKeyboardState;

protected override void Update(GameTime gameTime)
{
    KeyboardState keyboardState = Keyboard.GetState();

    // If the F1 key went down on this frame
    if(keyboardState.IsKeyDown(Keys.F1) && lastKeyboardState.IsKeyUp(Keys.F1))
    {
        help_on = !help_on; // Toggle the help_on variable
    }

    lastKeyboardState = keyboardState;

    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    if(help_on)
    {
        // Draw your help screen here
    }

    base.Draw(gameTime);
}