XNA 101 .Net

Learn how to program in C# while writing games in XNA Game Studio 3.0!
Our upcoming Silverlight book for beginners (includes a great chapter on game development in Silverlight!) Hello! Silverlight 2 with Dave Campbell, available online now!



Pages

Recent posts

Navigation

Archive

Blogroll

    Tampa Divorce Lawyer

    North of Tampa in Lutz, Florida. A Tampa Divorce Lawyer focusing on family, divorce, and real estate law.

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    Lesson 3: Sprites without Lymon

    Sprites are the building blocks for 2D games in XNA. If you've played any 2D games, you have seen sprites. Mario is a sprite. The Pac Man ghosts are sprites. Pretty much anything that moves in a 2D game is a sprite. In XNA, it's taken a step further. Pretty much anything that is displayed on the screen in a 2D XNA game, including a background image, is a sprite.

    Let me start off by apologizing for how technical this lesson turned out. I'm glossing over some things and skipping others, unfortunately in order to put together this simple sample there are some not-so-simple concepts that need to be introduced. The good news is that most of the real complicated stuff is stuff you can just copy verbatim for now and we'll cover the concepts in more depth going forward. Really focus on the code that goes in the Draw method, since that's what we'll be building on next time.  

    Here is a link to the MyFirstGame project for the following lesson including all code changes made during the lesson.

    http://www.bluerosegames.com/xna101/lessons/XnaLesson3.zip

    The Sprite Class

    Ok so since we have these things called sprites, there should be a class definition in XNA that we can instantiate to create Sprite objects, right? Well no, maybe it's because each game is going to have its own need when it comes to sprites, or maybe they're going to be added later to the XNA framework, but there isn't an actual Sprite class definition in XNA.

    Texture2D Objects

    Texture2D objects store images. Sprites are just images drawn on the screen, so the images that are drawn on the screen are stored in Texture2D objects. Typically you will create an image in a drawing program such as Photoshop, GIMP, Paint.NET, or even Paint, and load the image from the file into the Texture2D object.

    The Content Manager Class

    The ContentManager class is a key component to any XNA game. It handles the loading and management of the graphics content and the content pipeline. The content pipeline is what is used at design time (the time when you're writing the game) to easily bring in content assets created with other tools (MS Paint, Photoshop, 3D modelers,sound files, etc) and get them into a format understood by XNA and ready for packaging. 

    The SpriteBatch Class

    The SpriteBatch class is the key to sprite handling in XNA. To draw sprites, the following steps must be taken.

    1. Call Begin() on the SpriteBatch object.
    2. Call Draw() on the SpriteBatch object one or more times.
    3. Call End() on the SpriteBatch object.

    It is important to note that in XNA, performance is more closely tied to how many SpriteBatch Begin() and End() calls are made per frame and not how many Draw commands are called. So if you can do all of your drawing in one SpriteBatch, that is ideal. There are cases where you won't be able to do this, and we'll cover those in a future lesson.

    Let's Draw a Sprite

    In most programming languages, the first sample program is traditionally a "Hello World" program. In C# when building a Windows Forms application, the code will look something like:

    MessageBox.Show("Hello, World!");

    In graphics and game programming, it seems that the first program is typically displaying a ball on the screen and then animating it. So I won't break with tradition. Let's draw a ball.

    First we need an image. Save this image to your computer by right clicking and selecting "Save Target As..." or "Save Picture As..."

    All graphics and sound assets go in a special folder in your project. This folder is the Content folder. Right click on the Content folder in the MyFirstGame project in the Solution Explorer and select Add->Existing Item. Navigate to where you saved red_ball.bmp. Select it and click OK. The image is now part of your project and in the content pipeline. If you right click on red_ball.bmp in the Solution Explorer, and select Properties, you'll see some of the information that the content pipeline needs to process this file. Notice that the Asset Name is "red_ball". This is the name that we will use when referring to this image in the program. Also note that the asset name strips off the ".bmp" file extension.

    Now as I said above, we need a SpriteBatch object in order to draw a sprite. We also need a Texture2D object to store the image data in until we need it.

    Since we are going to need these objects repeatedly during the game, it makes sense to define them as variables in our Game1 class definiton. Variables defined as part of the Game1 class definition can be accessed from any of the Game1 methods.

    Below the lines in the file that look like this:

    public class Game1 : Microsoft.Xna.Framework.Game
    {

        SpriteBatch spriteBatch;

    Add the following:

    Texture2D spriteTexture;

    Notice that the SpriteBatch declaration is added for you. In Version 1 of XNA, you would have had to declare this yourself, but it was so common that they decided to help out a bit. This new line adds a Texture2D named spriteTexture to the Game1 class definition. Whenever we want to access either of these variables from a Game1 object, we will specify them by name. Now we need to instantiate these objects. Since they are graphics objects, we initialize them in the LoadContent method. So in the LoadGraphicsContent metod, right after the

    // TODO: use this.Content to load your game content here

    statement, add the following:

    spriteTexture = Content.Load<Texture2D>("red_ball");

    The Content object is an instance of the ContentManager class. The added statement calls  a method of the Content object in order to load a new Texture2D object from an image file. The asset name is being passed as an argument to the method. An argument is data that is passed to a method to help it do its job, or sometimes the data contained in the argument is modified by the method.

    This tells the ContentManager that we're loading an image, and the "red_ball" argument is the asset name of the content we are trying to load. The asset name is a string. Strings contain text values. In this particular case, we are passing a string literal also known as a string constant. String literals are always wrapped with double quotes in C#.

    Now that we have created our spriteTexture object, scroll down to the Draw() method and add the following after the line

    // TODO: Add your drawing code here

    spriteBatch.Begin();
    spriteBatch.Draw(spriteTexture, new Vector2(0f, 0f), Color.White);
    spriteBatch.End();

    So as stated previously, we need to begin our sprite batch, draw, and then end our sprite batch. To call a method of an object, specify the variable name for the object, followed by a period (.), followed by the method name to execute.

    For the Draw method, the arguments we pass to the method are the Texture2D object to draw, in our case it is the object named spriteTexture because this is what we defined it as at the top of the class definition, then the top left corner of the location to draw the sprite to (0f, 0f) is the upper left corner, and then the color to draw it with. If you draw with Color.White, the drawn sprite will be the same color as the original image. If you specify a color other than white, the drawn sprite will be tinted based on that color. 

    Build the program and run it again. You should see the red ball in the upper left corner.

    So why doesn't it have a magenta square around it? By default, XNA "masks out" any pixels that are pure magenta (full red and full blue color with no green). You could also use an image that supports transparent backgrounds, such as a PNG file. Here is an example of the same image as a PNG file with a transparent background:

    If you were to delete the red_ball.bmp from the solution and add red_ball.png, you would get a similar result as previously. One advantage to using an image in PNG format is that you could have parts of the image that are partially trasparent. This is useful for creating smooth edges around an image (known as anti-aliasing), as well as other effects. When drawn, the background behind the sprite would show though based on how transparent the image is.

    Posted: Oct 09 2008, 11:52 by Bill Reiss | Comments (7) RSS comment feed |
    • Currently 4.571429/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5
    Filed under:

    Comments

    Comments are closed