School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,148 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,742 people online right now. Registration is fast and FREE... Join Now!




XNA Sprite character animation.

 

XNA Sprite character animation., How to make a slimple sprite character Animation with XNA.

Hellbroth

27 Oct, 2009 - 05:06 AM
Post #1

D.I.C Head
**

Joined: 15 Aug, 2009
Posts: 53



Thanked: 1 times
My Contributions
Well i still don't like so much XNA but it's good and i want to learn it.Although i couldn't found any tutorials on how to make sprite sheets with characters animate.So i will post my code it's not commented but if you know at least the basic you will figure out everything.Sorry i am having University exams and i don't have time.

This is the character that we will animate.
IPB Image

And this is the source code :

CODE
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;

namespace WindowsGame6
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D texture;
        Point frameSize = new Point(32, 32);
        Point currentFrame = new Point(0, 0);
        Point sheetSize = new Point(3,4 );
        int timeSinceLastFrame = 0;
        int millisecondsPerFrame = 60;
        Vector2 pos1 = Vector2.Zero;
        float speed1 = 3f;


        

      
        

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 60);
            
            
            
        }

        

        
        /// <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
            GraphicsDevice device;
            graphics.PreferredBackBufferWidth = 500;
            graphics.PreferredBackBufferHeight = 192;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();
            Window.Title = "Animate Character Sprite";

            base.Initialize();
        }

        /// <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);
            texture = Content.Load<Texture2D>("man");
          
            

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

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

        /// <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();

            KeyboardState keyboardState = Keyboard.GetState();
            if (keyboardState.IsKeyDown(Keys.Up))
            {
                pos1.Y -= speed1;
                currentFrame.Y = 0;
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    if (currentFrame.Y >= sheetSize.Y)
                        currentFrame.Y = 0;
                    {
                        ++currentFrame.X;
                        if (currentFrame.X >= sheetSize.X)
                        {
                            currentFrame.X = 0;

                        }
                    }
                }

            }
            else  if (keyboardState.IsKeyDown(Keys.Down))
            {
                pos1.Y += speed1;
                currentFrame.Y = +2;
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    if (currentFrame.Y >= sheetSize.Y)
                        currentFrame.Y = 0;
                    {
                        ++currentFrame.X;
                        if (currentFrame.X >= sheetSize.X)
                        {
                            currentFrame.X = 0;

                        }
                    }
                }

            }
            else if (keyboardState.IsKeyDown(Keys.Right))
            {
                pos1.X += speed1;
                currentFrame.Y = +1;
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    if (currentFrame.Y >= sheetSize.Y)
                        currentFrame.Y = 0;
                    {
                        ++currentFrame.X;
                        if (currentFrame.X >= sheetSize.X)
                        {
                            currentFrame.X = 0;

                        }
                    }
                }
            }
            else if (keyboardState.IsKeyDown(Keys.Left))
            {
                pos1.X -= speed1;
                currentFrame.Y = +3;
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    if (currentFrame.Y >= sheetSize.Y)
                        currentFrame.Y = 0;
                    {
                        ++currentFrame.X;
                        if (currentFrame.X >= sheetSize.X)
                        {
                            currentFrame.X = 0;

                        }
                    }
                }
            }

            if (pos1.X < 0)
                pos1.X = 0;
            if (pos1.Y < 0)
                pos1.Y = 0;
            if (pos1.X > Window.ClientBounds.Width - frameSize.X)
                pos1.X = Window.ClientBounds.Width - frameSize.X;
            if (pos1.Y > Window.ClientBounds.Height - frameSize.Y)
                pos1.Y = Window.ClientBounds.Height - frameSize.Y;

            
            // TODO: Add your update logic here

            base.Update(gameTime);
        }
        
        /// <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)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin(SpriteBlendMode.AlphaBlend,
                SpriteSortMode.FrontToBack, SaveStateMode.None);
            spriteBatch.Draw(texture, pos1,
                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);
        }
        
    }
    
}



This might not be the best way to do it and i don't have any clues how to do it with a different way.At least it works for me. When i put a value in the currentFrame.Y it means that i want when i press that specific button it will go to that specific collumn of the sprite sheet. In this example i have 4 collumns and three frames for each collumn that referes to the Point sheetSize = new Point(3,4 );
When i have time i will comment it.

Hope it works for you too guys.

And a big Thanx to SixOfEleven for the GIMB tool suggestion now i can make transparent all my sprites.

This post has been edited by Hellbroth: 27 Oct, 2009 - 05:07 AM

User is offlineProfile CardPM
+Quote Post


SixOfEleven

RE: XNA Sprite Character Animation.

27 Oct, 2009 - 05:21 PM
Post #2

lives.ToCode();
Group Icon

Joined: 18 Oct, 2008
Posts: 3,066



Thanked: 171 times
Dream Kudos: 775
Expert In: C, C#, XNA, Game Programming, Programming Concepts

My Contributions
I have an alternative method for animating sprites. I borrowed an idea from Nick Gravelyn's Tile Engine tutorials. You can find links to those tutorials at http://nickgravelyn.com under the Archives page. I of course customized it to use my own coding style. I will write up a quick tutorial on just animating sprites for here at DIC as it is a common topic. Your idea was good but I will be taking an object-oriented approach and use a few classes for this to allow easy code reuse.
User is offlineProfile CardPM
+Quote Post

Hellbroth

RE: XNA Sprite Character Animation.

27 Oct, 2009 - 05:42 PM
Post #3

D.I.C Head
**

Joined: 15 Aug, 2009
Posts: 53



Thanked: 1 times
My Contributions
QUOTE(SixOfEleven @ 27 Oct, 2009 - 05:21 PM) *

I have an alternative method for animating sprites. I borrowed an idea from Nick Gravelyn's Tile Engine tutorials. You can find links to those tutorials at http://nickgravelyn.com under the Archives page. I of course customized it to use my own coding style. I will write up a quick tutorial on just animating sprites for here at DIC as it is a common topic. Your idea was good but I will be taking an object-oriented approach and use a few classes for this to allow easy code reuse.



You are complete right about using the classes.The problem for me although is that i first want to learn how to do things one at a time and then combine them and put them inside a class. For now i will just stick to this method and when i start putting more things like more items heroes houses etc. I will start using classes i am still learning the basics for the XNA as i don't have too much time now that the university has started. I am waiting for the next year where they actually start teaching how to program games etc even though i am realy dissapointed i don't think they can teach me something more than do documentation all the time and reference.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 04:09PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month