<< Chapter < Page
  Xna game studio     Page 12 / 12
Chapter >> Page >

Miscellaneous

This section contains a variety of miscellaneous information.

Housekeeping material
  • Module name: Xna0122-Frame Animation using a Sprite Sheet
  • File: Xna0122.htm
  • Published: 02/28/14
Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for thismodule at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should beaware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. Ineither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please beaware that it is a copy of a module that is freely available on cnx.org and that it was made and published withoutmy prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

Complete program listing

A complete listing of the XNA program discussed in this module is provided in Listing 14 .

Listing 14 . Class Game1 from the project named XNA0122Proj.

/*Project XNA0122Proj R.G.Baldwin, 12/28/09Animation demonstration. Animates a dog running, jumping, and stopping to ponder and scratch the ground. Uses twodifferent frame rates and a 5x2 sprite sheet. Runs back and forth across the game window always facing in theright direction. ********************************************************/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 XNA0122Proj { public class Game1 : Microsoft.Xna.Framework.Game {//Declare and populate instance variables GraphicsDeviceManager graphics;SpriteBatch spriteBatch; Texture2D myTexture;Vector2 spritePosition = new Vector2(0.0f,0.0f); int slide = 8;//Used to move sprite across screen.int scale = 4;//Size scale factor. int fast = 175;//Used for fast frame rate.int slow = 525;//Used for slow frame rate. int msPerFrame = 0;//Gets set for fast or slow.int msElapsed;//Time since last new frame. int spriteCol;//Sprite column counter.int spriteColLim = 5;//Number of sprite columns. int spriteRow;//Sprite row counter.int spriteRowLim = 2;//Number of sprite rows. int frameWidth;//Width of an individual imageint frameHeight;//Height of an individual image int xStart;//Corner of frame rectangleint yStart;//Corner of frame rectangle SpriteEffects noEffect = SpriteEffects.None;SpriteEffects flipEffect = SpriteEffects.FlipHorizontally;SpriteEffects spriteEffect;//noEffect or flipEffect int winWidth;//Width of the game window.int funSequenceCnt = 0; int pauseSequenceCnt = 0;public Game1() {//constructor graphics = new GraphicsDeviceManager(this);Content.RootDirectory = "Content"; //Set the size of the game window.graphics.PreferredBackBufferWidth = 450; graphics.PreferredBackBufferHeight = 100;}// end constructor protected override void Initialize() {//No special initialization needed base.Initialize();}//end Initialize protected override void LoadContent() {//Create a new SpriteBatch object, which can be // used to draw textures.spriteBatch = new SpriteBatch(GraphicsDevice); //Load the imagemyTexture = Content.Load<Texture2D>("dogcropped"); //Initialize instance variablesspriteCol = 0; spriteRow = 0;frameWidth = myTexture.Width / spriteColLim; frameHeight = myTexture.Height / spriteRowLim;msPerFrame = fast; spriteEffect = flipEffect;winWidth = Window.ClientBounds.Width; }//end LoadContentprotected override void UnloadContent() { //No unload code needed.}//end UnloadContent protected override void Update(GameTime gameTime) {// Allows the game to exit if(GamePad.GetState(PlayerIndex.One).Buttons.Back== ButtonState.Pressed) this.Exit();//-----------------------------------------------// //New code begins here.//Compute the elapsed time since the last new // frame. Draw a new frame only if this time// exceeds the desired frame interval given by // msPerFramemsElapsed += gameTime.ElapsedGameTime.Milliseconds; if(msElapsed>msPerFrame){ //Reset the elapsed time and draw the new frame.msElapsed = 0; //Compute the location of the next sprite to// draw from the sprite sheet. xStart = spriteCol * frameWidth;yStart = spriteRow * frameHeight; //Adjust sprite column and row counters to// prepare for the next iteration. if(++spriteCol == spriteColLim){//Column limit has been hit, reset the // column counterspriteCol = 0; //Increment the funSequenceCnt. The program// plays five cycles of the fun sequence with // the dog running and jumping using sprites// from row 0 of the sprite sheet. Then it // plays two cycles of the pause sequence// using sprites from row 1 of the sprite // sheet. Then the entire cycle repeats.funSequenceCnt++; if((funSequenceCnt == 5) || (spriteRow == 1)){spriteRow = 1;//advance to second row //Increment the pause sequence counter.pauseSequenceCnt++; //After two cycles in the pause mode, reset// variables and start the overall cycle // again.if(pauseSequenceCnt == 3){ spriteRow = 0;funSequenceCnt = 0; pauseSequenceCnt = 0;}//end if }//end if}//end if-else //Adjust position of sprite in the output window.//Also adjust the animation frame rate between // fast and slow depending on which set of five// sprite images will be drawn. if((spriteRow == 0) ||((spriteRow == 1)&&(spriteCol == 0))) { msPerFrame = fast;spritePosition.X += frameWidth * scale / slide; }else if ((spriteRow == 1) || ((spriteRow == 0)&&(spriteCol == 0))){ //Stop and display images.msPerFrame = slow; }//end if-else//Cause the image to move back and forth across // the game window always facing in the right// direction. if(spritePosition.X>winWidth - frameWidth * scale) {slide *= -1; spriteEffect = noEffect;}//end if if(spritePosition.X<0){ slide *= -1;spriteEffect = flipEffect; }//end if}//end if//-----------------------------------------------// //New code ends here.base.Update(gameTime); }//end Updateprotected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White);//Background//Select the sprite image from a rectangular area // on the sprite sheet and draw it in the game// window. Note that this sprite sheet has a white // non-transparent background.spriteBatch.Begin(); spriteBatch.Draw(myTexture,//sprite sheetspritePosition,//position to draw //Specify rectangular area of the// sprite sheet. new Rectangle(xStart,//Upper left corner yStart,// of rectangle.frameWidth, //Width and height frameHeight),// of rectangleColor.White,//Don't tint sprite 0.0f,//Don't rotate sprite//Origin of sprite. Can offset re // position above.new Vector2(0.0f,0.0f), //X and Y scale size scale factor.new Vector2(scale,scale), spriteEffect,//Face correctly0);//Layer number spriteBatch.End();//Required standard code. base.Draw(gameTime);}//end Draw method }//End class}//End namespace

-end-

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Xna game studio. OpenStax CNX. Feb 28, 2014 Download for free at https://legacy.cnx.org/content/col11634/1.6
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Xna game studio' conversation and receive update notifications?

Ask