Using Namepsaces This section lists the namespaces that the application will be using frequently. Saves the programmer from specifying a fully qualified name every time that a method that is contained within is used. (MSDN, 2012) New Namespace When you create a new game, XNA automatically creates a new namespace that is named whatever your game (filename) is named. In this example, the filename is “collision”. When you create a new game, your game is split into two projects Gamename and GamenameContent Collision Game1.cs holds the guts of your game (all pertinent actions) Program.cs holds the “Main” method which creates a new object of type “Game1” CollisionContent Holds your resources: images/sounds/effects, etc for game (reed, 2010) XNA generated code When your game is created, by default it will automatically create a constructor/class for Game1, a couple class level variables, and five other methods (initialize(), LoadContent(), UnloadContent(), Update(), Draw()) (reed, 2010). Class-level variables Class level variables can be used anywhere within the class (class we begin working with is Game1). Two class-level variables created by default: GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Don’t forget the syntax for declaring variables: VariableType VariableName; The variable type: GraphicsDeviceManager allows you to access the graphics device on your PC, Xbox 360, or Windows Phone 7 device (GraphicsDeviceManager has a property called “GraphicsDevice” that acts as a “pipeline” between the XNA game and the graphics card on your machine (GPU – Graphics Processing Unit); everything you do on the screen in your XNA game will run through this object The variable type: SpriteBatch allows you draw sprites (2D or 3D image integrated into a larger scene). (reed, 2010) The Five Methods Initialize Method is called first. It is used to initialize variables (set values) and other objects associated with the Game1 object. LoadContent Method is used to load any content (sounds, images, etc) needed for the game; called after the initialize method and any time the game needs to reload (player changes settings). (reed, 2010) After the LoadContent method is finished loading, your XNA game will enter into what is referred to as a “Game Loop”. The Game Loop consists only of the Update and Draw Method (called 60 times per second). When the game is exited (back button on gamepad, red X on window, or alt+F4) the UnloadContent method will start. XNA Game Cycle Initialize (reed, 2010) LoadContent Update Game Loop Draw UnloadContent Using the Draw and Update Methods All logic that will affect the game play should be in the Update or Draw method. The draw method (used to draw things) should only be used when drawing your seen. Everything else needed to run your game (moving objects, checking for collisions, updating scores, etc) should be coded in the Update method. (reed, 2010) Typical (nongame) development vs. Game development (VB .NET vs. XNA/C#) Nongame development is event-driven (waits for the user to do something; i.e. vb .NET = clickEvent, checkboxChangedE vent, etc.) (reed, 2010) Game development is “poll-driven”. The game is constantly looping (via game loop – draw/update) and “polling” to see if an event has taken place. Draw Method (reed, 2010) Protected is the access modifier. The protected modifier denotes that a member of a class is accessible only within that class and all derived classes. override is a keyword that denotes that the method overrides another method void is the return type (in this case, the method returns nothing) (http://bytes.com/topic/c-sharp/answers/375601-protected-override) Parameters are sets of data that are passed to a method. The method will not be able to use the information if it is not sent to it. Similar to forwarding e-mail/text msgs. The draw method receives a parameter. Type is GameTime, variable name is gameTime. This variable (which is also passed to the Update Method) is used to keep track of the time in the game. GameTime will be used later to help control framerate, animations, sounds, and other effects. The Clear method via the GraphicsDevice The Clear method erases everything on the screen and covers the screen with the color specified (i.e. CornflowerBlue). This screen is erased and draw 60 times per second. It is more efficient to erase and redraw everything 60 times per second, rather than keep track of everything that moves in a scene from one frame to the next, draw the moved items in their new locations, and draw whatever was behind the object previously…. 1. Each scene that is drawn (from draw method) is referred to as a frame. 2. Displaying frames (very quickly) gives the illusion of motion – persistence of vision; multiple frames make up an animation in a game. 3. The number of frames drawn per second is known as the “framerate” (60fps = 60 frames per second). (reed, 2010). Adding Sprites All graphics, sounds, effects, and other items are loaded in XNA through the “content pipeline”. This tool converts files (jpg, png, bmp, etc) into an XNA friendly format (reed, 2010). At this time please find an XNA logo (png) file from the internet. Save this file in your documents; name it: logo.png Once you have done this please go to your XNA game. Adding Sprites You should have a new game named collision (Windows Game 4.0) In the solution explorer, right-click “collisionContent”, click Add, and select a New Folder. Name your New Folder images Adding Sprites Right click your newly created images folder Click add and select “existing item”. Once the file window opens up, navigate to your logo file. Click add. Adding Sprites Your logo.png file should now appear within the images folder. Click on the logo.png file The properties should display at the bottom. You know there are no problems using your file if you see “Texture – XNA Framework” located in the Content Importer and Processor properties. A texture is a 2D image that will be applied to a surface; this will be discussed in more detail when we get to 3D objects. Please note the Asset Name (logo) not the filename (logo.png) is used to reference this file during runtime (this will be explained in further detail). Asset Names can be changed, but they must be unique (no duplicates). By creating subfolders (i.e. images) for your resources, you can use duplicate resource names in different folders (i.e. creating a sound called explosion and placing in a subfolder named “sound” and using an image named “explosion” and putting it in the “image” folder. (reed, 2010) Using your Sprite Now that content pipeline recognizes your image, it can be drawn on the screen. Before the image can be drawn, resources need to be loaded from the content pipeline into variables that can be manipulated. (reed, 2010) The default object used to store an image is Texture2D. We will add a variable named texture using this object/type Syntax: Texture2D texture; Declare this variable in the Game1 class (right beneath the graphics and spriteBatch variables). Creating the texture variable Your code should look like the code above This creates the variable (texture) to hold your image file in. (reed, 2010) The content property of the Game class is how you assign the image to the variable. As you can see from the code below, the Content.Load method is passed a parameter = the path to the image file. The @ symbol makes sure the string that follows (“ ”) is interpreted literally and ignores the escape sequences (/). (@”images/logo”) can also be written as (“images//logo”) Now that you have loaded your image file into your texture variable, it can be drawn on the screen. To the Draw Method we go! Drawing our Sprite Add the three lines of code: spriteBatch.Begin(); spriteBatch.Draw(texture, Vector2.Zero, Color.White); spriteBatch.End(); Your code should now resemble the code below. RUN THE PROGRAM….. Your screen should look like this: Let’s look at those last three lines…. (reed, 2010) All three lines are using the spriteBatch variable/object. It is of the “SpriteBatch” type and we defined earlier as a class-level variable And we instantiated (set) it as a new SpriteBatch (using the GraphicsDevice of the PC, Xbox, or Windows Phone 7 device) in the LoadContent method What’s happening? With Begin and End calls, the SpriteBatch object is telling (through XNA) the graphics device that it’s going to send it a sprite (or 2D image). The graphics device will receive large amounts of data throughout the XNA game, and the data will be in different formats and types. You have to let the graphics device know what kind of data is being sent. Thus, in order to call the spriteBatch.Draw method you must let the graphics card know the sprite data that is being sent, hence the texture, Vector2.Zero, and Color.White parameters that are passed to the method. (reed, 2010) spriteBatch.Draw parameters Parameter Type Description Texture Texture2D The Texture2D object that holds the image file you want to draw. Position Vector2 The position (in 2D coordinates) at which you want to begin drawing the image. The image is always drawn starting from the upper-left corner. Color Color The tinting color. Specifying White will not tint the image, whereas specifying any other color will cause the image drawn to be tinted with that color (try it). (reed, 2010) Vector2.Zero is a simplified way of saying new Vector2(0,0) with 0 for X and Y coordinates (X,Y) Vector2.Zero = new Vector2(0,0). In 2D the X,Y coordinate set to 0,0 is the upper-left corner of the screen. Coordinates move in positive X to the right and positive Y downward. Play with the coordinates to move the sprite/image. (reed, 2010) Centering the Image (reed, 2010) In order to center an image you must first find the center of the window and offset the upper-left corner coordinate appropriately. You can find the size by accessing the Window.ClientBounds property of the Game class. The Window.ClientBounds properties are always equal to the width and height of the window. Dividing this value by 2 will center the image. Your screen should look like this…. spriteBatch.Draw parameters (reed, 2010) Parameter Type Description texture Texture2D The texture to be drawn. Position Vector2 The coordinate for the upper-left corner of the drawn image. SourceRectangle Rectangle Allows you to draw only a portion of the source image. Use null for now. Color Color The tinting color. Rotation Float Rotates the image. Use 0 for now. Origin Vector2 Indicates an origin around which to rotate. Use Vector2.Zero for now. Scale Float Scales the image. Use 1f to draw the image the same size as the original image. For now use 1.5f (150% of image) Effects SpriteEffects Uses the SpriteEffects enum to flip the image horizontally or vertically. LayerDepth Float Allows you to specify which images are on top of other images. Use 0 for now. Let’s do it again! Search the web for a transparent XNA game or open up PhotoShop and make your XNA logo transparent. Save the file as: logo_transparent.png Load your file to the image folder in your XNA game Create a new variable of the Texture2D type named textureTransparent Instantiate your new variable to the file path of your image. Draw your new sprite beneath your texture sprite. (note: you only need one Begin and End for spriteBatch). Change the clear method to draw a black screen. Set spriteEffects to 0. References MSDN. (2012). Using Namespaces (C# Programming Guide). Retrieved on November 3, 2012 from http://msdn.microsoft.com/enus/library/dfb3cx8s.aspx Reed, Aaron (2010). Learning XNA 4.0. O’reilly Media, Inc.: ebook.