Would you like to react to this message? Create an account in a few clicks or log in to continue.

    Basics 2D - Sprites & Fundamentals

    avatar
    Admin
    Admin


    Posts : 77
    Join date : 2009-07-28

    Basics 2D - Sprites & Fundamentals Empty Basics 2D - Sprites & Fundamentals

    Post  Admin Tue Feb 02, 2010 5:34 pm

    When you create a new XNAproject, it has a game loop and program flow built-
    in. The game loop consists of an Update/Draw cycle, while the program flow adds
    steps at which the programmer can set game settings (Initialize), load graphics
    and sounds and other content (LoadContent), and perform special unload opera-
    tions (UnloadContent).

    Basics 2D - Sprites & Fundamentals 2441tnc
    avatar
    Admin
    Admin


    Posts : 77
    Join date : 2009-07-28

    Basics 2D - Sprites & Fundamentals Empty Re: Basics 2D - Sprites & Fundamentals

    Post  Admin Tue Feb 02, 2010 5:42 pm

    To draw an image on the screen, you need a Texture2D object that will hold the
    image in memory. The content pipeline prepares the image at compile time by
    converting it to an internal XNAformat. You then use a SpriteBatch object to
    draw the object on the screen.


    Basics 2D - Sprites & Fundamentals 30hty4z

    Code:
    texture = Content.Load<Texture2D>(@"Images/logo");
    The parameter passed into the Content.Load method is the path to the image file,
    starting with the Content node in Solution Explorer. When used in relation to
    strings, the @ symbol causes the string that follows to be interpreted literally, with
    escape sequences ignored. So, the following two lines of code will create the exact
    same string:

    Code:
    string str1 = @"images\logo";
    string str2 = "images\\logo";
    avatar
    Admin
    Admin


    Posts : 77
    Join date : 2009-07-28

    Basics 2D - Sprites & Fundamentals Empty Re: Basics 2D - Sprites & Fundamentals

    Post  Admin Tue Feb 02, 2010 5:44 pm

    To move something around the screen, you have to modify the position of that
    object between frames. Therefore, the first thing you need to do is start using a vari-
    able in place of the constant values you’ve been using to specify the objects’ posi-
    tions. Add two class-level Vector2 variable definitions (called pos1 and pos2) at the
    top of your class, and initialize both objects to Vector2.Zero:
    Code:
    Vector2 pos1 = Vector2.Zero;
    Vector2 pos2 = Vector2.Zero;
    You’ll also need to have a speed variable for each object. This variable will be used to
    determine how far you move each obect between frames. Add two float variables
    (called speed1 and speed2) below the Vector2 variables you just added:
    Code:
    float speed1 = 2f;
    float speed2 = 3f;
    Now, change the position parameters in each Draw method to use pos1 and pos2,
    respectively. Just to clean things up, set the second Draw call’s SpriteEffects parame-
    ter to SpriteEffects.None and change the scale parameter (third from the end) from
    1.5f to 1. This will remove the scaling and horizontal flipping that you implemented
    previously.
    Your two Draw calls now should look like this:
    Code:
    spriteBatch.Draw(texture,
        pos1,
        null,
        Color.White,
        0,
        Vector2.Zero,
        1,
        SpriteEffects.None,
        0);
    spriteBatch.Draw(textureTransparent,
        pos2,
        null,
        Color.White,
        0,
        Vector2.Zero,
        1,
        SpriteEffects.None,
        1);

    All sprites must be drawn between a SpriteBatch.Begin and a SpriteBatch.End
    call. These calls inform the graphics device that sprite information is being sent
    to the card. The Begin method has several overloads that allow you to change the
    way transparency is handled and the way sprites are sorted.


    Code:
                spriteBatch.Begin();
             
                spriteBatch.Draw(txtures[3], Vector2.Zero,
        new Rectangle(currentFrame.X * frameSize.X,
            currentFrame.Y * frameSize.Y,
            frameSize.X,
            frameSize.Y),
        Color.White, 0, Vector2.Zero,
        1, SpriteEffects.None, 0);
                spriteBatch.End();


    Last edited by Admin on Tue Feb 02, 2010 6:23 pm; edited 1 time in total
    avatar
    Admin
    Admin


    Posts : 77
    Join date : 2009-07-28

    Basics 2D - Sprites & Fundamentals Empty Sprite SHEETS

    Post  Admin Tue Feb 02, 2010 5:51 pm

    Animating sprites is typically done via a sprite sheet (a sheet containing multiple
    frames of sprite images drawn flipbook-style). Cycling through those images
    allows the sprite to appear animated.


    Sprite Sheet example :

    Basics 2D - Sprites & Fundamentals Princespriteswb3

    How to Cycle trough the sheet :

    • The height and width of each individual image (or frame) in the sprite sheet
    • The total number of rows and columns in the sprite sheet
    • An index indicating the current row and column of the image in the sprite sheet that should be drawn next

    the first frame in the sequence. Go ahead and add some class-level variables to reflect

    this data:
    Code:
    Point frameSize = new Point(75, 75);
    Point currentFrame = new Point(0, 0);
    Point sheetSize = new Point(6, 8);

    The Point struct works well for each of these variables because they all require a datatype that can represent a 2D coordinate (X and Y positions).

    Code:
    ++currentFrame.X;
    if (currentFrame.X >= sheetSize.X)
    {
        currentFrame.X = 0;
        ++currentFrame.Y;
        if (currentFrame.Y >= sheetSize.Y)
            currentFrame.Y = 0;
    }

    All this code does is increment the X property of the CurrentFrame object and then
    check to make sure it isn’t greater than or equal to the number of frame columns. If
    it is greater than the number of columns, it resets the X property to 0 and increments
    the Y value to draw the next row of sprites in the sheet. Finally, if the Y value exceeds
    the number of rows in the sheet, it resets Y to 0, which starts the entire animation
    sequence over starting with frame (0, 0).
    avatar
    Admin
    Admin


    Posts : 77
    Join date : 2009-07-28

    Basics 2D - Sprites & Fundamentals Empty Re: Basics 2D - Sprites & Fundamentals

    Post  Admin Tue Feb 02, 2010 5:53 pm

    The default framerate of an XNAgame is 60 fps. Changing that value will affect
    sprite animations that do not use a separate timer to determine animation speed
    as well as the overall game speed.
    • To adjust the animation speed of an individual sprite, you can set a counter to
    keep track of the last time you changed frames and only change frames every X
    number of milliseconds.Test Your Knowledge: Exercise | 39
    • While the default framerate in XNAdraws a new frame every 16 milliseconds,
    that is nothing compared to the default framerate of Chuck Norris’s fists. On
    average, Chuck’s fists punch and mortally wound enemies every 4 milliseconds.
    avatar
    Admin
    Admin


    Posts : 77
    Join date : 2009-07-28

    Basics 2D - Sprites & Fundamentals Empty QCM

    Post  Admin Tue Feb 02, 2010 5:59 pm

    1. What are the steps in an XNA game loop?
    • The XNA game loop consists of only two methods: Update and Draw.

    2. If you wanted to load a Texture2D object, in which method should you do that?
    • LoadContent.

    3. What line of code should you use to change the framerate of an XNAgame to 20
    fps?

    • Either of these lines will do the trick:
    TargetElapsedTime = TimeSpan.FromMilliseconds(50);
    TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 50);

    4. What should you pass in as the parameter of Content.Load when loading a
    Texture2D object

    • The asset name of the texture image you want to load. You can find an
    image’s asset name by viewing its properties in Solution Explorer.

    5. Fact or fiction: the content pipeline will let you know at compile time if you add an image to your project that it cannot parse.
    • Fact. The content pipeline runs a compilation step on all content (textures,
    models, sounds, etc.) and then outputs the result as an XNA-compatible for-
    matted object. If this step fails during compilation, the result is a compila-
    tion error.

    6. You’re drawing a sprite, and you want the background to be transparent. What
    steps do you need to take to draw it with a transparent background?

    • There are two ways to draw transparent images in XNA. The first option has
    two requirements. First, the background of your image itself must be trans-
    parent. If it isn’t, you’ll need to edit the image in an image editor and give it
    a transparent background. Second, SpriteBlendMode.AlphaBlend must be
    used (this is the default if no parameters are specified in SpriteBatch.Begin).
    The second option is to make sure that the transparent portion of the image
    is solid magenta (255, 0, 255).

    7. You have two sprites (Aand B), and when they collide you always want Ato be
    drawn on top of B. What do you need to do?

    • There are two possible solutions: using SpriteSortMode.FrontToBack, you
    can set the layer depth of Ato a value greater than that of B (both must be
    within the range of 0 to 1); or, using SpriteSortMode.BackToFront, you can
    set the layer depth of A to a value lower than that of B.

    8. What are the things you need to keep track of to cycle through a sprite sheet?
    • Current frame to draw, size of each individual frame, and number of col-
    umns and rows in your sprite sheet.
    avatar
    Admin
    Admin


    Posts : 77
    Join date : 2009-07-28

    Basics 2D - Sprites & Fundamentals Empty Exercice

    Post  Admin Tue Feb 02, 2010 6:05 pm

    Problem :


    1. In this chapter, you built an example where two XNAlogo images moved
    around the screen and bounced off the edges. Take the animated sprite example
    that you built at the end of this chapter and make the animated sprite move and
    bounce in a similar fashion—but in this case, make the animated sprite move in
    both X and Y directions and bounce off of all four edges of the screen.
    3

    This exercise is fairly straightforward, as it involves taking two examples
    from the chapter and merging pieces together. The animation aspect of the
    exercise is covered at the end of the chapter, while the movement and
    bouncing off screen edges is covered in the middle of the chapter.Chapter 2: Fun with Sprites | 427
    One thing that may be tricky is moving in both X and Y directions at the
    same time. In the previous moving example, you used a float variable for the
    speed and added it to either the X or the Y coordinate depending on which
    sprite you were moving (they both moved in only one direction).
    Now I’d recommend using a Vector2 to represent speed. That way you can
    have different values for speed in the X direction and the Y direction. Also,
    you can add your Vector2 speed to your Vector2 position by simply adding
    the two together (you can add Vector2 objects just as you would add integer
    or float values).
    The other catch to this exercise is that in the previous moving example you
    used the size of the Texture2D object to determine how far from the edge of
    the screen to bounce in the other direction, but now the size of your
    Texture2D object will be inaccurate because you’re using a sprite sheet.
    Instead, you’ll want to use the size of an individual frame within that sprite
    sheet to detect when the image has hit the edge of the screen.
    Here is one possible solution for this exercise:
    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.Media;
    using Microsoft.Xna.Framework.Net;
    using Microsoft.Xna.Framework.Storage;
    Code:
    namespace AnimatedSprites
    {
        public class Game1 : Microsoft.Xna.Framework.Game
        {
            GraphicsDeviceManager graphics;
            SpriteBatch spriteBatch;
            Texture2D texture;
            Point frameSize = new Point(75, 75);
            Point currentFrame = new Point(0, 0);
            Point sheetSize = new Point(6, 8);
            //Framerate stuff
            int timeSinceLastFrame = 0;
            int millisecondsPerFrame = 16;
            //Speed and movement
            Vector2 speed = new Vector2(5, 2);
            Vector2 position = Vector2.Zero;
            public Game1()428 | Appendix: Answers to Quizzes and Exercises
            {
                graphics = new GraphicsDeviceManager(this);
                Content.RootDirectory = "Content";
            }
            protected override void Initialize()
            {
                // TODO: Add your initialization logic here
                base.Initialize();
            }
            protected override void LoadContent()
            {
                // Create a new SpriteBatch, which can be used to draw textures.
                spriteBatch = new SpriteBatch(GraphicsDevice);
                texture = Content.Load<Texture2D>(@"imageshreerings");
            }
            protected override void UnloadContent()
            {
                // TODO: Unload any non ContentManager content here
            }
            protected override void Update(GameTime gameTime)
            {
                // Allows the game to exit
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
                  ButtonState.Pressed)
                    this.Exit();
                //Update time since last frame and only
                //change animation if framerate expired
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    ++currentFrame.X;
                    if (currentFrame.X >= sheetSize.X)
                    {
                        currentFrame.X = 0;
                        ++currentFrame.Y;
                        if (currentFrame.Y >= sheetSize.Y)
                            currentFrame.Y = 0;
                    }
                }
                //Move sprite
                position += speed;
                //If the sprite hit a wall, reverse direction
                if (position.X > Window.ClientBounds.Width - frameSize.X ||Chapter 3: User Input and Collision Detection | 429
                    position.X < 0)
                    speed.X *= -1;
                if (position.Y > Window.ClientBounds.Height - frameSize.Y ||
                    position.Y < 0)
                    speed.Y *= -1;
                base.Update(gameTime);
            }
            protected override void Draw(GameTime gameTime)
            {
                GraphicsDevice.Clear(Color.White);
                spriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                    SpriteSortMode.FrontToBack, SaveStateMode.None);
                spriteBatch.Draw(texture, position,
                    new Rectangle(currentFrame.X * frameSize.X,
                        currentFrame.Y * frameSize.Y,
                        frameSize.X,
                        frameSize.Y),
                        Color.White, 0, Vector2.Zero,
                        1, SpriteEffects.None, 0);
                spriteBatch.End();
                base.Draw(gameTime);
            }
        }
    }

    Sponsored content


    Basics 2D - Sprites & Fundamentals Empty Re: Basics 2D - Sprites & Fundamentals

    Post  Sponsored content

      Similar topics

      -

      Current date/time is Mon May 20, 2024 9:46 am