How to create an XNA Framework app for Windows Phone

[This documentation is preliminary and is subject to change.]

July 06, 2012

Applies to: Windows Phone 8 Developer Preview | Windows Phone OS 7.1

This topic shows you how to create the basic functionality of the XNA Framework application that is used throughout this series. The application is a simple game. When you have completed this topic, you will have built an application that moves a square graphic object around the screen. Subsequent topics in this series will expand on this basic infrastructure, adding collision detection, adding levels to the game, and adding a scoreboard to show the current score and current level. Once this complete game is in place, a trial experience will be added.

Note

The steps in the following procedure are for Visual Studio 2010 Express for Windows Phone. You may see some minor variations in menu commands or window layouts when you are using the add-in for Visual Studio 2010 Professional or Visual Studio 2010 Ultimate.

This topic contains the following sections.

  • Prerequisites
  • Creating a New Project
  • Adding Content
  • Adding the Basic Game Logic
  • Next Topic

Prerequisites

Make sure you have downloaded and installed the Windows Phone SDK. For more information, see Installing the Windows Phone SDK .

Creating a New Project

The first step in creating an XNA Framework application for Windows Phone is to create a new project.

To create a new project

  1. Launch Visual Studio 2010 Express for Windows Phone from the Windows Start menu. If the Registration window appears, you can register or temporarily dismiss it.

  2. Create a new project by selecting the File | New Project menu command.

  3. The New Project window will be displayed. Expand the Visual C# templates, and then select the XNA Game Studio 4.0 templates.

  4. Select the Windows Phone Game (4.0) template. Fill in the project Name as desired. You can also specify the Location and Solution name or leave the default values.

    GetStartedNewProjectXNA

  5. Click OK. The Windows Phone Platform selection window will appear. Select Windows Phone 7.1 for the Target Windows Phone Version.

    GetStartedSelectPlatformXNA

  6. Click OK. A new project will be created and the Game1.cs source file will be opened in Visual Studio.

Adding Content

The next step is to add content to your project, in this case a graphic object.

To add content to the project

  1. Make sure the Solution Explorer is visible in Visual Studio. If it is not visible, select View | Other Windows | Solution Explorer to make it appear.

  2. This example will use the PhoneGameThumb.png file that was created by default in this project in the WindowsPhoneGame1\WindowsPhoneGame1\WindowsPhoneGame1 directory. You can use either PhoneGameThumb.png or your own graphic file, but for best results, the graphic object should be approximately 64 x 64 pixels in size.

    In the Solution Explorer , right-click the Content node, in this case named WindowsPhoneGame1Content (Content) , and select Add | Existing Item. Browse to your graphic file, in this case named WindowsPhoneGame1\WindowsPhoneGame1\WindowsPhoneGame1\ PhoneGameThumb.png , and click Add. The graphic object will be added to the project.

    Select the graphic name in the Solution Explorer and then look at the file properties in the Properties window. Note the Asset Name of the graphic object, in this case PhoneGameThumb.

    GetStartedPropertiesXNA

Adding the Basic Game Logic

In this step, you will add the code that will move a graphic object around the screen. The following code is responsible for:

  • Adding some variables.

  • Loading your graphic object in the LoadContent method.

  • Drawing your graphic object on the screen in the Draw loop.

  • Updating the position of your graphic object in the Update loop.

To add the basic game logic

  1. Replace the code for the Game1 class in Game1.cs with the following code. This is the basic game logic that moves a sprite object around the screen.

        public class Game1 : Microsoft.Xna.Framework.Game
        {
            GraphicsDeviceManager graphics;
            SpriteBatch spriteBatch;
    
            Texture2D texture;
            Vector2 spritePosition;
            Vector2 spriteSpeed;
            int sprite1Height;
            int sprite1Width;
    
            public Game1()
            {
                graphics = new GraphicsDeviceManager(this);
                graphics.PreferredBackBufferWidth = 800;
                graphics.PreferredBackBufferHeight = 480;
                graphics.IsFullScreen = true;
                graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
    
                Content.RootDirectory = "Content";
    
                // Frame rate is 30 fps by default for Windows Phone.
                TargetElapsedTime = TimeSpan.FromMilliseconds(33.3333);
    
            }
    
            /// <summary>
            /// Allows the game to perform any initialization it needs to before starting to run.
            /// This is where it can query for any required services and load any non-graphic
            /// related content.  Calling base.Initialize will enumerate through any components
            /// and initialize them as well.
            /// </summary>
            protected override void Initialize()
            {
                spriteSpeed = new Vector2(50.0f, 50.0f);
                base.Initialize();
            }
    
            /// <summary>
            /// LoadContent will be called once per game and is the place to load
            /// all of your content.
            /// </summary>
            protected override void LoadContent()
            {
                // Create a new SpriteBatch, which can be used to draw textures.
                spriteBatch = new SpriteBatch(GraphicsDevice);
    
                texture = Content.Load<Texture2D>("PhoneGameThumb");
    
                spritePosition.X = 0;
                spritePosition.Y = 0;
    
                sprite1Height = texture.Bounds.Height;
                sprite1Width = texture.Bounds.Width;
    
            }
    
            /// <summary>
            /// UnloadContent will be called once per game and is the place to unload
            /// all content.
            /// </summary>
            protected override void UnloadContent()
            {
                // TODO: Unload any non ContentManager content here
            }
    
            /// <summary>
            /// Allows the game to run logic such as updating the world,
            /// checking for collisions, gathering input, and playing audio.
            /// </summary>
            /// <param name="gameTime">Provides a snapshot of timing values.</param>
            protected override void Update(GameTime gameTime)
            {
                // Allow the game to exit.
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
                    ButtonState.Pressed)
                    this.Exit();
    
                // Move the sprite around.
                UpdateSprite(gameTime, ref spritePosition, ref spriteSpeed);
                base.Update(gameTime);
    
            }
    
            void UpdateSprite(GameTime gameTime, ref Vector2 spritePosition, ref Vector2 spriteSpeed)
            {
                // Move the sprite by speed, scaled by elapsed time.
                spritePosition +=
                    spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
    
                int MaxX =
                    graphics.GraphicsDevice.Viewport.Width - texture.Width;
                int MinX = 0;
                int MaxY =
                    graphics.GraphicsDevice.Viewport.Height - texture.Height;
                int MinY = 0;
    
                // Check for bounce.
                if (spritePosition.X > MaxX)
                {
                    spriteSpeed.X *= -1;
                    spritePosition.X = MaxX;
                }
    
                else if (spritePosition.X < MinX)
                {
                    spriteSpeed.X *= -1;
                    spritePosition.X = MinX;
                }
    
                if (spritePosition.Y > MaxY)
                {
                    spriteSpeed.Y *= -1;
                    spritePosition.Y = MaxY;
                }
    
                else if (spritePosition.Y < MinY)
                {
                    spriteSpeed.Y *= -1;
                    spritePosition.Y = MinY;
                }
    
            }
    
            /// <summary>
            /// This is called when the game should draw itself.
            /// </summary>
            /// <param name="gameTime">Provides a snapshot of timing values.</param>
            protected override void Draw(GameTime gameTime)
            {
                graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
    
                // Draw the sprite.
                spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
    
                spriteBatch.Draw(texture, spritePosition, Color.White);
                spriteBatch.End();  
    
                // Call the Draw method on the scoreBoard object to update the scoreboard.
                base.Draw(gameTime);
    
            }
    
        }
    
  2. Build the solution by selecting the Build | Build Solution menu command. The project should build without any errors. You can open the Error List window, if it is not already open, by selecting the View | Error List menu command. If there are errors, review the steps above, correct any errors, and then build the solution again.

  3. On the standard toolbar, set the deployment target of the application to Windows Phone Emulator .

    Target on Standard Toolbar selecting emulator

  4. Run the application by selecting the Debug | Start Debugging menu command. This will open the emulator window and launch the application. You will see a graphic bounce around the screen.

  5. If the emulator times out into the lock screen, you can unlock it by clicking at the bottom of the screen and swiping upward.

  6. You can set debug breakpoints in the code by placing the cursor on the desired line of code and selecting the Debug | Toggle Breakpoint menu command.

  7. To stop debugging, select the Debug | Stop Debugging menu command.

The basic functionality for the XNA Framework application has now been defined. The game consists of a square graphic object that bounces around the screen. In subsequent topics in this series, the functionality of the game will be enhanced. Game play will consist of the user trying to tap the square as it moves around the screen, recording each hit, or collision, as the user’s score. Detection of the user tapping the graphic on the screen is described in the next section. In addition to detecting the user tapping the object, a scoreboard will be created to display the user’s current score as well as a mechanism to play multiple levels of the game. After this infrastructure is in place, a trial mode will be implemented that detects the current license of the game and allows the user to play only level one, if the game is in trial mode.

Next Topic

The next topic in this series will demonstrate how to add collision detection to the application. This will form the basis of the game play for this application. Each time the user taps the moving object on the screen, the number of hits, or collisions, will be increased and recorded as the score of the game.

How to add collision detection to an XNA Framework app for Windows Phone