简体   繁体   中英

XNA C# - How to make a button pressed without being pressed

I've got a starting image which, when you press enter, it goes to the game. The problem is that since this is an image, the button has to be held down in order to stay showing the game screen. Is there a way to make it so that once you press the button, the image stays off?

Update Method:

helpScreen = new HelpScreen(this); 

if (!helpScreen.gamestarted && Keyboard.GetState().IsKeyDown(Keys.Enter))
{
    helpScreen.gamestarted = true;
}

Draw Method:

if (!helpScreen.gamestarted)
{
    helpScreen.Draw(spriteBatch);
}

Store the state in your main game class:

private bool gameStarted = false;

In your update method check the input:

if (!gameStarted && Keyboard.GetState().IsKeyDown(Keys.Enter))
{
    gameStarted = true;
}

Later in your draw method only draw the start image, if the game has not been started yet:

if (!gameStarted)
{
    helpScreen.Draw(spriteBatch);
}

That way it will not be drawn again, once the player pressed the button. Also using a general gameStarted field clarifies your intentions and you can base other game logic on its state in a simple and natural way.

Can I ask, have you done any other coding surrounding input? Or are you beginning with this help screen? Because this covers the very basics of input handling.

It seems like you are looking at this as an event driven system, when in fact it is a game loop. This means that you check a value each loop and base your output on that, rather than by events (eg. Click)

What I would do is record the previous value, then in the next loop, compare that value against the current value. Example in your Update method:

//Outside of Update loop declare
KeyboardState previousState = Keyboard.GetState();

//Inside update loop
if (Keyboard.GetState().IsKeyUp(Keys.Enter) && previousState.IsKeyDown(Keys.Enter))
{
        helpScreen = null;     }

This will trigger when the Enter button has been pressed and released. There are many other changes that I would perform on that code, but this should point you in the right direction for this particular problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM