GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment...

23
C# XNA Bouncing Ball First Game Part 1 GAME:IT Advanced

Transcript of GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment...

Page 1: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

C# XNA Bouncing Ball

First Game – Part 1

GAME:IT Advanced

Page 2: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Objectives By the end of this lesson, you will have learned

about and will be able to apply the following XNA

Game Studio 4.0 concepts.

• Intro XNA Game Studio 4.0

• Overview of XNA Game Concepts

• Review the core game methods and events

• Review the Bouncing Ball Code

Page 3: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360, Windows, and Windows Phone. XNA Game Studio includes the XNA Framework, which is a set of managed libraries designed for game development purposes. These libraries have been built with the Microsoft .NET Framework, which means they integrate with all versions of Visual Studio, including Visual C# Express. Some of the game development features provided by XNA Game Studio and the XNA Framework include:

• 2D and 3D graphics / textures

• Enhanced Audio / Video Playback

• Networking / Multi-player support

• Xbox Live Features

• Windows Phone-specific Feature Support

• Data Access / Storage

Page 4: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Before you begin:

1. Open MyFirstGame_Tutorial solution.

2. Confirm that you can successfully build the solution. Refer to the setup file if you have trouble building the solution.

3. Expand the projects and verify the files match the files on the right.

4. In Part 1 of the lesson we will be reviewing the core components and fundamentals that make up every XNA game.

5. In Part 2 of the lesson we will extend upon the MyFirstGame project that was previously completed or downloaded and setup as a starting point.

Page 5: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Game application entry point

1. Click and open Program.cs

2. The Program class in an XNA game project

is similar to that of a console application. The Main method only performs one function, and that is to launch the game.

3. The using statement is used to instantiate an instance of Game1 and call its Run method. When the game exits, the using statement ensures it releases its resources. /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { using (Game1 game = new Game1()) { game.Run(); } }

Page 6: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

XNA Game application overview 1. Click and open Game1.cs 2. By default, when you create an XNA game

application, both Program.cs and Game1.cs are automatically created.

3. The Content project is also created by default and it sets up a place to store media and content files used in the game.

4. There are a number of methods in the Game1 class that will appear by default as overrides from the base class Game. Another nice feature is that the methods and events have been documented with a summary of intended purpose and function. Be sure to read this information to help you better understand the purpose and structure.

5. Starting from the top down, we will briefly review each of the following: – Using Statements – Inheritance – Game1 Constructor – Initialize – LoadContent – UnloadContent – Update – Draw – UpdateSprite

Page 7: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Using Statements – Game1.cs

using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Media;

Note: The using statements reference the Microsoft XNA Framework libraries that the Game1 class can make use of. If you recall from previous lessons, this allows you to refer to the type names directly without having to reference the type along with the namespace in code. It keeps the code much cleaner. The libraries are added as references to the XNA game project by default. The installation of XNA game studio installs them locally on your computer and therefore allows them to be referenced from your project and in turn at the class level.

Page 8: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Inheritance – Game1.cs

namespace MyFirstGame { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game {

Note: Game1 inherits from Microsoft.Xna.Framework.Game, which means it takes on all the properties, methods, events and other members from this class giving Game1 the core functionality it needs to build a XNA game from. From the Program.cs class, Game1 calls the Run method, which is defined in the base type Game. The run method initializes the game, begins running the game loop, and starts processing the events for the game. Many of these events appear as overrides in the Game1 class.

Page 9: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Constructor – Game1.cs

GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; }

Note: The Game1 constructor does not take in any parameters by default. If we had an overloaded constructor with parameters, we would need to pass those in from the Program.cs class at the time Game1 is instantiated. Above the constructor there are a couple of class level variables declared. The constructor instantiates a new GraphicsDeviceManager class passing in this, or the Game1 class as parameter of type Game. The constructor also sets the Content.RootDirectory, which refers to the MyFirstGameContent project. Clicking on MyFirstGameContent, you will notice the name Content in the properties window, which is what this refers to.

Page 10: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Initialize – Game1.cs

/// <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() { // TODO: Add your initialization logic here base.Initialize(); }

Note: Initialize is called after the Game and GraphicsDevice are created, but before LoadContent. As the summary points out, you can load non-graphic content such as sound effects.

Page 11: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

LoadContent – Game1.cs

/// <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); myTexture = Content.Load<Texture2D>("mytexture"); }

Note: LoadContent is called when graphics resources need to be loaded. The spriteBatch is instantiated here. What is a sprite? A sprite is a image or texture that is integrated into the game. A game can be made up of many sprites and a SpriteBatch simply enables a group of sprites to be drawn with the same settings. myTexture is of type Texture2D and is added to the spriteBatch and drawn to the screen in the Draw method. Content.Load loads the texture from the Content project and refers to the texture by its Asset Name. You can view the Asset Name by selecting the texture and viewing the properties window.

Page 12: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

UnloadContent – Game1.cs

/// <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 }

Note: UnloadContent is called when graphics resources need to be unloaded. Override this method to unload any game-specific graphics resources. One recommendation for this method is to call the Dispose method on any resources that were initialized in the LoadContent method. If a graphics device was to reset, this method would be called to cleanup resources and free up memory and then LoadContent would be called again.

Page 13: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Update & Draw Method Summary The Update and Draw methods make up what can be described as the Game loop. These methods are called multiple times a second. The Update method is used to call game logic while the Draw method is used to draw the game. Executing at multiple times a second provides the game the ability to perform many code operations a second while moving graphics on the screen. The number of times the Draw method executes per second is known as the games FPS or frame rate per second. The Update and Draw methods can be setup as Fixed Step or Variable Step. The default is Fixed Step and is set with the Game.IsFixedTimeStep property. In Fixed Step mode, it will call Update with every Tick method specified by the interval in Game.TargetElapsedTime. In Fixed Step mode it’s possible to have multiple calls to the Update method for every Draw method call on slower computers. The reason this can occur is that the computer running the game attempts to catch up to the clock’s TargetElapsedTime and skips Draw in order to do so. In Variable Step mode, the game does not try to maintain the frame rate and therefore there is a one-to-one ratio between Update and Draw. The GameWindow sometimes calls Paint for certain situations, which results in the possibility of Draw being called more than Update.

Page 14: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Update – Game1.cs

/// <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) { // Allows the game to exit if(GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); #if WINDOWS if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); #endif

Page 15: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Update – Game1.cs (continued)

// Move the sprite around. UpdateSprite(gameTime); base.Update(gameTime); }

Note: The MyFirstGame project does not have a lot going on in the Update method, but there are a few notable statements. There are a couple of conditional statements that deal with input from the user in order to exit the game. this.Exit(); refers to the Game1 class and thus calls Exit on the base class Game. #if WINDOWS is a conditional compilation symbol that only calls the code within the statement if the game is a Windows Game. The same code is often used for Xbox, Windows, and Windows mobile games so #if XBOX and #if WINDOWS_PHONE are also available. UpdateSprite is a local method not an override from Game. This helper method is responsible for the logic that changes the position of the Sprite. The position change of the Sprite is not reflected in the game window until the Draw method is called, which is generally called right after Update.

Page 16: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Draw – Game1.cs

/// <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(myTexture, spritePosition, Color.White); spriteBatch.End(); base.Draw(gameTime); }

Page 17: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Draw – Game1.cs (continued)

Note: The Draw method is used for the game-rendering specific code. It’s important that you call the base.Draw method in order to enumerate through any graphics that were added to the Components collection. Remember that base refers to the base class, even though you override a method from the base class, sometimes you still want to call the base method. You will see base calls used throughout XNA development. GraphicsDevice.Clear flushes the graphics in the window and sets the background color. This method is called first in the Draw method in order to clear the window. Any new sprites will be added on top of the color specified. spriteBatch.Begin, .Draw, and .End is used to render the Texture2D sprite to the window. The Begin method takes in sort mode and BlendState. The default color BlendState is AlphaBlend. Draw simply specifies the sprite texture, position, and color. The color is used to tint a sprite. Use Color.White for full color with no tinting.

Page 18: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

UpdateSprite – Game1.cs

void UpdateSprite(GameTime gameTime) { // Move the sprite by speed, scaled by elapsed time. spritePosition += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;

Note: The UpdateSprite method is where all the logic happens to change the position of the sprite and prepares it to be redrawn in the Draw method. Both spritePosition and spriteSpeed are Vector2 graphics, which means they have x and y coordinates. The spritePosition adds the value of the result of the fixed spriteSpeed value of x=50 and y=50 multiplied by the ElapsedGameTime TotalSeconds. This represents a fraction of a second since the Update method is called several times a second, usually 60 or more on most computers. This means that the spritePosition moves a small amount every few milliseconds, which makes for a smooth moving graphic at a steady speed. Example: 50 * TotalSeconds(0.0166667 ) = 0.833335. A spritePosition of x=100, y=100 would be x=100.833335,y=100.833335 in 17 milliseconds at a 60 FPS.

Page 19: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

XNA Game Window

Page 20: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Note: As the photo depicts, X is 0 at the left edge of the window and 800 at the right edge of the window. The value is in pixels. The value of Y is 0 at the top and 480 at the bottom of the window. The upper left hand corner would be X=0,Y=0 and the lower right hand corner would be X=800,Y=480. The change in value of X and Y determines the angle of movement the graphic is traveling in. This assumes a window size of 800 x 480. The window size may vary depending on the game, monitor, and settings. You can also set the size of the window with code. A graphic with a X or Y coordinate outside the range of the window will not show after a draw method. Setting negative values for X and Y is a technique that can be used to bring graphics in your game on and off the screen between draw method calls.

Page 21: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

UpdateSprite – Game1.cs (continued)

int MaxX = graphics.GraphicsDevice.Viewport.Width - myTexture.Width; int MinX = 0; int MaxY = graphics.GraphicsDevice.Viewport.Height - myTexture.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; }

Page 22: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

UpdateSprite – Game1.cs (continued)

if (spritePosition.Y > MaxY) { spriteSpeed.Y *= -1; spritePosition.Y = MaxY; } else if (spritePosition.Y < MinY) { spriteSpeed.Y *= -1; spritePosition.Y = MinY; } }

Note: MaxX,MaxY,MinX, and MinY establish the range for the game window. The rest of the conditional logic compares the current position of x and y and if the min or max is true, it sets the position and reverses the direction by multiplying the value of spriteSpeed x or y by -1. Recall that spriteSpeed is used in calculating the spritePosition. Adding a negative value to a positive number causes the position of x or y to move towards 0. This technique causes the bounce effect and remains true to Newton’s 3rd law of motion.

Page 23: GAME:IT Advanced - stemfuse.com · XNA Game Studio XNA Game Studio is a programming environment integrated with Visual Studio that allows you to create 2D and 3D games for Xbox 360,

Explore Concepts Learned (optional)

Visit: http://msdn.microsoft.com/en-us/library/default.aspx

Search for keywords in part 1 of this lesson: Xna game class, xna game update, xna game draw, xna SpriteBatch, xna Texture2D, xna graphics, etc. Visit: http://create.msdn.com/en-US

Explore the APP HUB for Windows, Phone, and Xbox Games.