简体   繁体   English

XNA C#-如何在不被按下的情况下按下按钮

[英]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. 我有一个起始图像,当您按Enter键时,它将进入游戏。 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: 如果游戏尚未开始,则稍后在draw方法中仅绘制开始图像:

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. 还可以使用一般的gameStarted字段来阐明您的意图,并且可以以简单自然的方式将其他游戏逻辑基于其状态。

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: 您的Update方法中的示例:

//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. 当按下并释放Enter按钮时,将触发此操作。 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. 我将对该代码执行许多其他更改,但这应为您指出此特定问题的正确方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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