fun with xna o’reilly breakdown (learning xna 4.0 – aaron reed)

Download Fun With XNA O’Reilly Breakdown (learning  xna  4.0 –  aaron  reed)

If you can't read please download the document

Upload: kyros

Post on 25-Feb-2016

41 views

Category:

Documents


0 download

DESCRIPTION

Fun With XNA O’Reilly Breakdown (learning xna 4.0 – aaron reed). 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. - PowerPoint PPT Presentation

TRANSCRIPT

Fun With XNA OReilly Breakdown

Fun With XNAOReilly Breakdown(learning xna 4.0 aaron reed)Using NamepsacesThis 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 NamespaceWhen 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 projectsGamename and GamenameContentCollisionGame1.cs holds the guts of your game (all pertinent actions)Program.cs holds the Main method which creates a new object of type Game1CollisionContentHolds your resources: images/sounds/effects, etc for game(reed, 2010)

XNA generated codeWhen 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 variablesClass 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;Dont 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 objectThe variable type: SpriteBatch allows you draw sprites (2D or 3D image integrated into a larger scene).

(reed, 2010)

The Five MethodsInitialize 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).

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.

(reed, 2010)

XNA Game CycleInitializeUpdateDrawLoadContentUnloadContentGameLoop(reed, 2010)

Using the Draw and Update MethodsAll 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, checkboxChangedEvent, etc.)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.(reed, 2010)

Draw MethodProtected is the access modifier. The protected modifier denotes that amember of a class is accessible only within that class and all derivedclasses.

override is a keyword that denotes that the method overrides anothermethod

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.

(reed, 2010)

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.Each scene that is drawn (from draw method) is referred to as a frame.Displaying frames (very quickly) gives the illusion of motion persistence of vision; multiple frames make up an animation in a game. The number of frames drawn per second is known as the framerate (60fps = 60 frames per second). (reed, 2010).

Adding SpritesAll 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.pngOnce you have done this please go to your XNA game.

Adding SpritesYou 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 SpritesRight click your newly created images folderClick add and select existing item.Once the file window opens up, navigate to your logo file.Click add.

Adding SpritesYour logo.png file should now appear within the images folder.Click on the logo.png fileThe 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 SpriteNow 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.

The default object used to store an image is Texture2D. We will add a variable named texture using this object/typeSyntax:Texture2D texture;Declare this variable in the Game1 class (right beneath the graphics and spriteBatch variables).(reed, 2010)

Creating the texture variableYour code should look like the code aboveThis creates the variable (texture) to hold your image file in.

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!(reed, 2010)

Drawing our SpriteAdd 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:

Lets look at those last three lines. 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(reed, 2010)

Whats happening?With Begin and End calls, the SpriteBatch object is telling (through XNA) the graphics device that its 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 parametersParameterTypeDescriptionTextureTexture2DThe Texture2D object that holds the image file you want to draw.PositionVector2The position (in 2D coordinates) at which you want to begin drawing the image. The image is always drawn starting from the upper-left corner.ColorColorThe 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 ImageIn 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.

(reed, 2010)

Your screen should look like this.

spriteBatch.Draw parametersParameterTypeDescriptiontextureTexture2DThe texture to be drawn.PositionVector2The coordinate for the upper-left corner of the drawn image.SourceRectangleRectangleAllows you to draw only a portion of the source image. Use null for now.ColorColorThe tinting color.RotationFloatRotates the image. Use 0 for now.OriginVector2Indicates an origin around which to rotate. Use Vector2.Zero for now.ScaleFloatScales the image. Use 1f to draw the image the same size as the original image. For now use 1.5f (150% of image)EffectsSpriteEffectsUses the SpriteEffects enum to flip the image horizontally or vertically.LayerDepthFloatAllows you to specify which images are on top of other images. Use 0 for now.(reed, 2010)

Lets 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.pngLoad your file to the image folder in your XNA gameCreate a new variable of the Texture2D type named textureTransparentInstantiate 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.ReferencesMSDN. (2012). Using Namespaces (C# Programming Guide). Retrieved on November 3, 2012 from http://msdn.microsoft.com/en-us/library/dfb3cx8s.aspxReed, Aaron (2010). Learning XNA 4.0. Oreilly Media, Inc.: ebook.