วันพุธที่ 9 พฤษภาคม พ.ศ. 2555

How to: Create Your First XNA Framework Application for Windows Phone

How to: Create Your First XNA Framework Application for Windows Phone

           
This topic introduces you to the steps needed to create a basic XNA Framework application for Windows Phone. You can find this completed Hello XNA Framework sample in Code Samples for Windows Phone.
NoteNote:
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.

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

To create a new project

  1. Make sure you have downloaded and installed the Windows Phone SDK. For more information, see Installing the Windows Phone SDK.
  2. 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.
  3. Create a new project by selecting the File | New Project menu command.
  4. The New Project window will be displayed. Expand the Visual C# templates, and then select the XNA Game Studio 4.0 templates.
  5. 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
  6. Click OK. The Windows Phone Platform selection window will appear. Select Windows Phone 7.1 for the Target Windows Phone Version.
    GetStartedSelectPlatformXNA
  7. Click OK. A new project will be created and the Game1.cs source file will be opened in Visual Studio.

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

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. The first item to add is a graphic file. 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.
    Right-click the Content node, in this case named WindowsPhoneGame1Content (Content), and select Add | Existing Item. Browse to your graphic file – in this case 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
  3. The next step is to add a sound file. This example will use the Windows Ding.wav sound file that ships with Microsoft Windows 7. Search for Windows Ding.wav on your computer and copy it to the WindowsPhoneGame1\WindowsPhoneGame1\WindowsPhoneGame1 directory. You can also use your own sound file, but a very short sound about 1 second long is preferred.
    Right-click the Content node, in this case named WindowsPhoneGame1Content (Content), and select Add | Existing Item. Browse to your sound file – in this case WindowsPhoneGame1\WindowsPhoneGame1\WindowsPhoneGame1\Windows Ding.wav and click Add. The sound file will be added to the project.
    Select the sound file in the Solution Explorer and then look at the file properties in the Properties window. Note the Asset Name of the sound, in this case Windows Ding.

In this step, you will add the code that will move two graphic objects around the screen, detect when the graphic objects collide, and play a sound when the graphic objects collide. Look at the code that was added for you by default in the project. The framework of the game application has been provided. The next steps will take you through the process of:
  • Adding some variables.
  • Loading your graphic objects and sound assets in the LoadContent method.
  • Drawing your graphic objects on the screen in the Draw loop.
  • Updating the position of the graphic objects and detecting a collision in the Update loop.

To add code

  1. Copy and paste the following variables into your Game1 class and place the variables after the existing SpriteBatch spriteBatch variable. There are pairs of variables to track each graphic object, its position, its speed, its height, and its width. There is also one variable to hold our sound effect.
            Texture2D texture1;
            Texture2D texture2;
            Vector2 spritePosition1;
            Vector2 spritePosition2;
            Vector2 spriteSpeed1 = new Vector2(50.0f, 50.0f);
            Vector2 spriteSpeed2 = new Vector2(100.0f, 100.0f);
            int sprite1Height;
            int sprite1Width;
            int sprite2Height;
            int sprite2Width;
    
            SoundEffect soundEffect;
    
    
  2. Replace the LoadContent method with the following lines of code. This code will load the graphic object twice. Later on, you can add a second graphic object to the project so that you can have two different graphic objects bouncing about the screen. Each graphic object is given an initial position on the screen and the height and width of each are calculated.
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
    
        texture1 = Content.Load<Texture2D>("PhoneGameThumb");
        texture2 = Content.Load<Texture2D>("PhoneGameThumb");
      
        soundEffect = Content.Load<SoundEffect>("Windows Ding");
    
        spritePosition1.X = 0;
        spritePosition1.Y = 0;
    
        spritePosition2.X = graphics.GraphicsDevice.Viewport.Width - texture1.Width;
        spritePosition2.Y = graphics.GraphicsDevice.Viewport.Height - texture1.Height;
    
        sprite1Height = texture1.Bounds.Height;
        sprite1Width = texture1.Bounds.Width;
    
        sprite2Height = texture2.Bounds.Height;
        sprite2Width = texture2.Bounds.Width;
    }
    
    
  3. Replace the Draw method with the following lines of code. This code will draw each graphic object on the screen at its current position. They are given a different BlendState so that they appear slightly different since this example uses the same graphic file for each sprite.
    protected override void Draw(GameTime gameTime)
    {
        graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
    
        // Draw the sprite.
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
        spriteBatch.Draw(texture1, spritePosition1, Color.White);
        spriteBatch.End();
    
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.Opaque);
        spriteBatch.Draw(texture2, spritePosition2, Color.Gray);
        spriteBatch.End();
    
        base.Draw(gameTime);
    
    }
    
    
  4. Replace the Update method with the following lines of code. The code also adds the UpdateSprite and CheckForCollision methods. The new code in the Update method will instruct each sprite to update their position in the UpdateSprite method. The UpdateSprite method also checks to see if the sprite hits a side, and if it does, changes its direction. Finally, Update calls CheckForCollision which checks to see if the bounds of each graphic object intersect with each other. If they do, a sound is played.
    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 spritePosition1, ref spriteSpeed1);
        UpdateSprite(gameTime, ref spritePosition2, ref spriteSpeed2);
        CheckForCollision();
    
        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 - texture1.Width;
        int MinX = 0;
        int MaxY =
            graphics.GraphicsDevice.Viewport.Height - texture1.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;
        }
    
    }
    
    void CheckForCollision()
    {
        BoundingBox bb1 = new BoundingBox(new Vector3(spritePosition1.X - (sprite1Width / 2), spritePosition1.Y - (sprite1Height / 2), 0), new Vector3(spritePosition1.X + (sprite1Width / 2), spritePosition1.Y + (sprite1Height / 2), 0));
    
        BoundingBox bb2 = new BoundingBox(new Vector3(spritePosition2.X - (sprite2Width / 2), spritePosition2.Y - (sprite2Height / 2), 0), new Vector3(spritePosition2.X + (sprite2Width / 2), spritePosition2.Y + (sprite2Height / 2), 0));
    
        if (bb1.Intersects(bb2))
        {
            soundEffect.Play();
        }
    
    }
    
    
    

The application is now complete. This step will let you build, run, and debug the application.

To build and debug the application

  1. Build the solution by selecting the Debug | Build Solution menu command. The project should build without any errors in the Error List windows. You can open the Error List window, if it is not already open, by selecting the View | Other Windows | Error List menu command. If there are errors, review the preceding steps, correct any errors, and then build the solution again.
  2. On the standard toolbar, set the deployment target of the application to Windows Phone Emulator.
    Target on Standard Toolbar selecting emulator
  3. Run the application by selecting the Debug | Start Debugging menu command. This will open the emulator window and launch the application. You will see two graphics bounce around the screen and play a sound when they are intersecting.
    GetStartedFirstAppRunningXNA
  4. If the emulator times out into the lock screen, you can unlock it by clicking at the bottom of the screen and swiping upward.
  5. 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.
  6. To stop debugging, select the Debug | Stop Debugging menu command.
You have now created a basic XNA Framework application for Windows Phone. For more information about XNA Game Studio development, see XNA Game Studio 4.0.

ไม่มีความคิดเห็น:

แสดงความคิดเห็น