Friday, 14 September 2012

Managing Game States in XNA (Menus)

While in a game making competition at the beginning of the year and in the room where my team was placed was one other team, a team of first year programmers.

For the most part they did ok with all four of them working together considering the limited amount of programming experience they had between them.

Later on in the competition there seemed to be a massive fuss coming from them all, they had a programming problem which they hadn't solved all night long...

Being neighbourly I asked what their problem was and if I could help at all.

All night the team had been working on implementing a simple menu system in there game and they where all working on different things. This gave me an idea to write a small guide on how to set a very simple screen management system in XNA.

The basic idea of this menu system is to have an enumerated type with all of the menu/game states.

enum GameState {MainMenu, InGame, EndGame, Pause}
GameState gameState = GameState.MainMenu;

Add this to the top of your Game1 class for a game with all menus mentioned above.

Now inside your Update method...
switch(gameState)
{
case GameState.MainMenu:
break;

case GameState.InGame:
break;

case GameState.EndGame:
break;

case GameState.Pause:
break;
}
Now if you add the exact same thing to your Draw method you have complete control over what is drawn and updated depending on the current status of the game.
I would put this between

spriteBatch.Begin();

And

spriteBatch.End();

This is because in my research I found it to be much more efficient to open the SpriteBatch as few times as possible.

Anyway to change the current state just update the gameState variable and all of the code should update too.
Thanks for reading,
Antshockey

3 comments:

  1. It's awesome for me to have a web page, which is good in support of my know-how. thanks admin

    Feel free to surf to my page ... Bukkit 1.5.1

    ReplyDelete
  2. Normally I don't read post on blogs, but I wish to say that this write-up very pressured me to try and do so! Your writing style has been amazed me. Thank you, very nice article.

    My web-site - Path of Exile

    ReplyDelete
  3. Hmm is anyone else encountering problems with the pictures on this blog loading?
    I'm trying to figure out if its a problem on my end or if it's the blog.
    Any feedback would be greatly appreciated.

    Look at my blog :: Feed The Beast

    ReplyDelete

Please leave a comment if you've found this tutorial helpful or if you're facing any problems and I will endeavour to assist you.