Skip to content

XNA 2D Beginner Tutorial – Adding Simple Menu Systems

February 4, 2010


Note:

This tutorial is an add on to the tutorials on how to make a cannon game to shoot down aliens that was produced by Microsoft. The original tutorial and source code is here. Please go through that tutorial and get the basic code structure, then come back and follow my tutorial. This was produced mainly for the OC, but you can easily edit it to use for the XBOX.

What You Will Be Trying To Create:

With this tutorial, you will be able to create a menu system that is seen when the game starts, and when you pause. It will be able to resume the game, and exit the game screen. After you follow this tutorial, you will be able to add additional functionalities like the ability to start different games from one menu screen, or have an options menu that you can edit game settings in. Remember this is just a basic menu, it is your responsibility to use this code to make more advanced menu’s. So have fun reading it, because I am having fun teaching it.

How this tutorial will be notated:

It is pretty simple, I will tell you which function to look in, and after which command in the function. This is all based on the source code at the end of the tutorial that Microsoft created, so we will all be on the same page when I say what to put where.

Let’s get started:

Basic Idea

First thing we need to do is talk about the basic idea of our menu. Assuming you payed any attention to the Microsoft tutorial, then you should know what variables are.

How this menu works, is you have a variable that holds the number of the state that the game is in. For example, you have an int named stateNum. In this tutorial, you will only have two states. (Menu state, and game state.) So the variable will need to hold two variables which will be ’0′ and ’1′.( ’0′ for the menu, and ’1′ for the game.)

The games Draw and Update call will execute code based on that number. So if you have stateNum set to ’0′, then it will only execute code that corresponds to the menu, and if you have stateNum set to ’1′ it will execute game code. Take a look at this, if you are confused then this should help a little bit.

DRAW Method

if stateNum is equal to ’0′

then execute this code

else if stateNum is equal to ’1′

then execute this code

Nothing to hard there right? Then to get back and forth from the menu and the game, you just need to make a function that switches the value of stateNum. So, lets get started actually coding this beast, and I will explain some more details along the way.

Initial Code:

This will be in Game1.cs. Enter this line of code over the red line on the image below.

int stateNum = 0;

After you do that, then go down to your Update function. We will start putting our logic in here.

Start by adding this line  “else if(stateNum == 1) {” Above

” GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);”, and close it off with a ” } “

on the line before “previousGamePadState = gamePadState;”. Then right above all of that,
make one more if statement
Like this; “if(stateNum == 0)  { }”. Keep it blank for now though, but we will be adding our menu logic there later. Next jump down to the Draw function. Which should look like this.

And we will do a similar sectioning method like we did in the update method. Identical actually…
Go to the line that says “spriteBatch.Draw(backgroundTexture, viewportRect,Color.White);”,
and right above it make an if statement like this.

“if (stateNum == 1) {” then finish the code block by putting a curly brace right BEFORE

“spriteBatch.End();” .
Then add another “if(stateNum == 0)  { }”.

At this point if you run the game, it will be a blank screen. What you need to do now is
create functions in both of your update states that change the
variable to the other number. It’s pretty easy, so lets get started.

Changing States:

What needs to happen here, is you need to go into each state code block and add a function that switches to the other state.
So if you are in state one, than you move to state zero. And vise versa…
To do this you need to enter this line of code at the beginning of state one:
if (previousKeyboardState.IsKeyUp(Keys.Enter) && keyboardState.IsKeyDown(Keys.Enter))
{
stateSelection = 0;
}
Then this at the beginning of state zero:

if (previousKeyboardState.IsKeyUp(Keys.Enter) && keyboardState.IsKeyDown(Keys.Enter))
{

stateSelection = 1;

}

If you compile at this point, you can switch between your game, and the blank screen. This is progress. :)

But unless you want to look at a blank screen, lets make it pretty and functional.

Adding Pictures:

You need to add some pictures to your menu background to make it pretty. This is pretty simple, all you

need to do is draw a background like you did with the game back ground. In fact, we use the same variable

for placement. After you add some pictures to your content pipeline and load them in to a variable called menuBackground, go in your Draw method, in your state zero.

And just add this line of code. spriteBatch.Draw(menuBackground,viewportRect, Color.White);
When you switch between the game and the menu, you will see a background. For reference, you can use the background from my cannon game.

Just right click and save as. You now have a decent looking menu background, so maybe its time to add some buttons!

Buttons:

First thing we need for this section, is we need to make some buttons. So I will post the images below, and you can use them as much as you want. Just right click and save as.

After you have saved those and thrown them into your content pipeline. And add a texture2d variable to them named startButton, and exitButton. Then add these two Vector2′s for the position.

Vector2 exitButtonDrawPoint = new Vector2(400, 380);
Vector2 resumeButtonDrawPoint = new Vector2(400, 300);

Then add one more image to your content pipeline.

It is a little hard to see, but there is a picture up above this text. So right click it and save as. Add a texture 2d variable called selector, and your good. No need for a Vector2 for its position,  because we will be setting its position to the position of the menu button we want selected. From now on, I will be doing less of the coding for you. I want to see if you can remember simple coding techniques.

Drop down to your Draw method, in your state ’0′. And add the draw code for your buttons, with the position variables that you created earlier. And remember, you do not need to add another spriteBatch.begin(), because both of the two states will be in the original spritebatch call. When you compile this, you will see that the buttons are a little off center. I like the look of this personally, but you can change where the buttons are if you like. It would not effect the way this tutorial plays out.

You need to add these variables at the top where you declare everything else.

int menuSelection = 0;
int amntMenuButtons = 1;

And in your Draw method, in state zero you need to add an if statement. I want you to write the code out yourself.

Here is what it should do. It should check to see if the menu selection is zero or one. If its zero, then it will draw the selector at the position of the start button, and if its one, then it will draw at the position of the exit button. You done? Well, now you need to be able to switch the menuSelection variable from zero to one and back.

Just jump to your update call in state zero, and add a few more if statements. They should look like this.

if (previousKeyboardState.IsKeyUp(Keys.Down) && keyboardState.IsKeyDown(Keys.Down))
{
menuSelection += 1;
}

if (previousKeyboardState.IsKeyUp(Keys.Up) && keyboardState.IsKeyDown(Keys.Up))
{
menuSelection -= 1;
}
All that does, is it adds one to menu selection, and subtracts one. Adds when you press down, and subtracts when you press up. So if you run it now, it will move the selector from one button to the other and it will disappear. But to fix this, you need to limit change the way menuSelection works. But this is the end of part one. I hope you come back tomorrow because part two is on the way. But for now you should try to mess around with the code you have learned here. And add a few things, like additional buttons. In the next lesson, we will add functionality to the buttons. And we will be done!

End of Part One:


6 Comments leave one →
  1. Fernando permalink
    March 29, 2010 7:49 pm

    This Isn’t Done In A Simple Way.

    Why Not Show The File Before And After The Editing So I Can See What Really Happens… Instead Of Random Line Plug Ins.

  2. mike permalink
    April 14, 2010 4:06 pm

    All i want is to look at the code to see how they did it.

    I have a hard time believing it was written by a programmer, they usually do things better.

    • kadajett permalink*
      April 14, 2010 7:20 pm

      What would you like me to show you?

      • mike permalink
        April 15, 2010 3:23 pm

        Less paragraphs of explaining what the code does, more just showing the code. If anyone is making menus they should at least be literate in the language, removing the need to explain what each line of code is doing.

        In making a menu system I have been trying to find different ways other people have done it for some ideas and it is much easier to just look at 50 lines of code than read an essay.

      • kadajett permalink*
        April 22, 2010 6:59 pm

        I have actually just used this in one of my new projects. If the team agrees, I will post the source code for you all to see. I hope it will help you better understand what I am doing, or make better use of it.
        I apologize if I haven’t been replying as fast as I should have, I have been dealing with school and whatnot.

  3. mike permalink
    April 17, 2010 3:07 am

    I made a menu system quick not the best but it works for what i needed.
    Your paragraphs were helpful, I just find it easier to read code.
    Some bits of code for how I did it.

    i made a simple MenuItem.cs
    class MenuItem : DrawableGameComponent
    {
    public int type; // 0=text, 1=slide bar
    public string text;
    public int height;
    public int Value; // used for slider bar items;

    public MenuItem(Game game, int _type, string _text)
    : base(game)

    My Menu.cs is basically a List : DrawableGameComponent with an int selected
    the Draw function of my Menu.cs

    public override void Draw(GameTime gameTime)
    {
    if(visible)
    {
    spriteBatch.Begin();
    for (int i = 0; i < menu.Count; i++)
    {
    if (i == selected)//selected item has extra padding, is larget and yellow
    {
    loc.Y += 10;
    spriteBatch.DrawString(spriteFont, menu[i].Text, loc, Color.Yellow, 0, new Vector2(0, 0), 1.7f, SpriteEffects.None, 0);
    loc.Y += 10;
    }
    else
    {
    spriteBatch.DrawString(spriteFont, menu[i].Text, loc, Color.White, 0, new Vector2(0, 0), 1.5f, SpriteEffects.None, 0);
    }
    if (menu[i].Type == 1)//makes a slider bar. block is a white box *.bmp
    {
    int width = 8 * menu[i].Height;
    spriteBatch.Draw(block, new Vector2(loc.X, loc.Y + menu[i].Height), null, Color.Red, 0,
    new Vector2(0, 0), new Vector2(width * menu[i].Value / 100, menu[i].Height * .6f), SpriteEffects.None, .1f);
    }
    loc.Y += menu[i].Height;
    }
    spriteBatch.End();
    } }

    then with an int GameState to manage if the menu or game is active I manage the menus like:

    if (mainMenu.visible)
    {
    if (current.Buttons.A == ButtonState.Pressed && past.Buttons.A != ButtonState.Pressed)//A button
    {
    switch (mainMenu.selected)
    {
    case 0://newgame
    lastMenu = mainMenu;//lastMenu is for when B is pressed.
    newGameMenu.visible = true;
    mainMenu.visible = false;
    break;
    case 1://options
    lastMenu = mainMenu;
    optionsMenu.visible = true;
    mainMenu.visible = false;
    break;
    case 2://exit
    lastMenu = mainMenu;
    exitConfirm.visible = true;
    mainMenu.visible = false;
    break;
    } } }

Leave a Reply

Note: You can use basic XHTML in your comments.

Subscribe to this comment feed via RSS