Animation made easy in MonoGame with TexturePacker

Hello! It’s been far too long since my last blog post, however I’ve had nothing interesting to say – that is until now! Today I will talk about the latest version of TexturePacker, which has a new export option specifically for MonoGame – thus allowing you to easily create animations within your MonoGame apps.

For those who just want to see the results straight away, here is a video of the iOS simulator running a MonoGame animation produced with the help of TexturePacker…

Below I will walk you through how to produce the above application. Also a link will be provided to the source code.

TexturePacker

I’ve mentioned TexturePacker in a previous blog post however, for those that haven’t used it before, it is a very easy to use application for creating Texture Atlases / Sprite Sheets. The idea is that you draw the individual frames of animation for your game characters as separate image files – and then drag and drop them into TexturePacker – whereupon you end up with a single image file and accompanying data file ready to load into your game. Using a single sprite sheet is much more efficient than loading lots of individual images in game development. (See this fun video from the makers of TexturePacker that explains it better than I can)

SpriteSheets – TheMovie – Part 1 by CodeAndWeb

Now the above maybe nothing new to a lot of people, however what you might not know, is that the latest version of TexturePacker has an option for exporting the sprite sheet and data file in a format targeted at MonoGame – along with access to source code for loading and handling the resultant data files within your MonoGame app. This means that all the hard work of loading the sprite sheet and rendering the correct frame is taken care of for you – as described further below…

So, let’s get started…

First step – Download a copy of TexturePacker from here and load it up. You’ll be presented with a screen like below…

TexturePacker-NewProject

Select the MonoGame option and then ‘Create Project’ to move forward…

TexturePacker-CreateProject

Next gather your individual images together into a logical folder structure. E.g. folder name based on the animation type. Then drag and drop the parent folder into TexturePacker. (For the purposes of this tutorial I am using a set of images from my demonstration project on GitHub here).

Immediately you’ll see that TexturePacker has grouped all the images together, as below…

TexturePacker-Sprites

Now, the final steps, before hitting the ‘publish’ button to create your sprite sheet data, is to alter a few settings depending on your requirements. I will explain the few that we will use in this tutorial, however an extensive set of documentation can be found here.

TexturePacker-Settings

Scaling Variants

In a later section within this tutorial I will walk you through creating a MonoGame app, targeting iOS, using Xamarin Studio. Those who have done iOS development before will know that you should create two versions of your graphics – a high resolution version for retina screens and a ‘normal resolution’ graphics file for non-retina screens – and by appending @2x to the end of the retina file, iOS will take care of ensuring the appropriate graphics file is used at run-time.
If you are targeting iOS with MonoGame then this is no different. MonoGame will automatically load the @2x version when run on a retina device.
This is where the ‘Scaling Variants’ feature comes in useful. Rather than having to produce two versions of your graphics files and use TexturePacker twice to export separate sprite sheets for retina and non-retina, you are able to tell TexturePacker to do all of this for you.

So, let’s do that now! Click on the ‘Scaling Variants’ cog and you’ll be presented with the following screen.

TexturePacker-ScalingVariants

Change the Preset option to be generic @2x and then click on the ‘Add’ button to get a second box. Fill in the details as below.

TexturePacker-ScalingVariantsPopulated

Click Apply and then Close.

Hopefully the above screen shot was pretty self-explanatory, however in summary we are telling TexturePacker to produce two versions of the sprite sheet – one with a scale of 1 (retina version) and one with a scale of 0.5 (non retina version) – and the Variant Name is @2x. (The variant name is used later when we specify the filenames for export).

Of course, if you are targeting a platform (or device) that only has support for a single resolution then you won’t need to use the ‘Scaling Variants’ option – however for iOS, for example, this option makes it very easy.

Trim Mode

If you scroll down the TexturePacker options you’ll see a Sprites section…

TexturePacker-SettingsTrimMode

The first option is the ‘trim mode’ option. Already set to ‘trim’, this will remove any transparent borders around each individual frame, thus reducing the overall size of the sprite sheet. I would therefore suggest keeping this set to ‘trim’ rather than ‘none’. Also, handling the trimming of the frames at runtime is taken care of for us by the TexturePacker MonoGame Loader code – as described later!

Pivot Points

This option serves two purposes…

  • Firstly it dictates which point on each frame should be positioned at the location that we choose to render that frame. For example, if you choose a pivot point of centre and you choose to render a frame at location 100, 100 then it is the centre of the frame that is positioned at 100, 100. However if you choose a pivot point of top left then it is the top left hand corner of the frame that is positioned at location 100, 100. Generally speaking I would choose centre as my pivot point.
  • The pivot point also dictates where the point of rotation should be if we rotated a frame at runtime. Should it be the Top-Left corner of the frame or the centre etc. If you don’t need to rotate a frame at runtime then it doesn’t matter.

Export Files

Next let’s take a look at the three different files that are produced by TexturePacker when we create our sprite sheet…

TexturePacker-SettingsExportFiles

Initially blank, these fields need to be populated as per the screenshot and explanation below…

TexturePacker-SettingsExportFilesPopulated

The Texture file is the graphics / sprite sheet file. Above you can see I have set the name of this file to be CapGuyDemo{v}.png. The main point of interest here is the {v} – this will be replaced at the time of export by the variant name as configured in the Scaling Variants optjon above. Thus, we will end up with two PNG files – one called CapGuyDemo@2x.png and the other called CapGupDemo.png. Just by configuring the Scaling Variants option and placing the {v} in the filename, this is handled for us.

The Data file is the accompanying file that contains the location, trim, rotation and pivot point information for each individual frame/sprite within the sprite sheet. As, in this example, there are two different sprite sheets produced by TexturePacker – retina and non-retina – then so we will need two different data files. Therefore again we include the {v} in the filename.

Finally the Class file is a file containing a c# class which simply contains a series of constants referring to each individual frame. Later you will see that within our MonoGame app we need to reference each frame by its ‘string name’ however a runtime error would occur if we had a typo, or if we specified the name of a frame that we accidentally forgot to drag into TexturePacker. Therefore we use the const strings defined in the below file to reference a particular frame – thus if we refer to a const string that does not exist then we’ll get a compile time error which can be resolved straight away as opposed to a run time error that would not occur until deployed and running on the target device(s).
This will become clearer when we build the MonoGame app later.

Code-ClassFile

One point worth noting at this stage is to give some thought to the location of the above three files. You might want to specify the appropriate location within the source code to avoid an extra step of copying them later. i.e. the Data file and the Texture file ultimately need to end up in the Content folder – and the class file needs to go ‘somewhere’ in your app source tree.

As I stated above, there are more options within TexturePacker, however for the purposes of this tutorial we will leave it at that for now and proceed to the next step. Therefore save your TexturePacker project and then hit publish to export all you sprite sheet(s) and data files(s) and the class file.

TexturePacker Loader

Before we delve into writing our demo MonoGame app it is worth first talking about the TexturePacker Loader source code. The TexturePacker Loader is free to use and can be obtained either from Nuget or direct from Github (or, in the future, the Xamarin component store). If installing from Nuget or cloning direct from Github you’ll get the source code.

Most Nuget packages are a library DLL that just gets referenced into your project, however this Nuget package actually brings in the complete TexturePackerLoader source code – It’s only 4 source files so it’s quite easy to follow and understand – and, as such, advanced users have the option of making their own changes should they wish.

TexturePackerLoader-ProjectFiles

Now, I’m not going to delve deeply into the TexturePacker Loader explaining every single line of code – instead I will give an overview of how to use the loader.

Sprite Sheet Loader

The first step you’ll want to take when creating a new MonoGame application is to load your sprite sheet(s) along with any other assets. As such this is likely to be done in the LoadContent method of your main Game class.
Simply instantiate a new instance of the SpriteSheetLoader class and call the Load method passing in the name of your sprite sheet (as produced by TexturePacker), something like below…

Code-SpriteSheetLoader

You will now have a reference to a SpriteSheet. I’d suggest this is a class level variable as it will be required in your draw method as described below…

Sprite Render

The other main class that the TexturePacker Loader gives us is the SpriteRender class. This class handles the positioning and drawing of our sprites on screen. In its simplest form all you have to do is specify which frame / image to draw and at what position – however you also have the power, if you so desire, to specify the colour, rotation, scale and whether the image should be flipped.
Again I would recommend instantiating the one instance of this class in your LoadContent method like below…

Code-SpriteBatchAndRender

…and then in your draw method you simply render frames on screen something like this…

Code-Draw

In the above example we are drawing the frame / image labeled Capguy_turn_0002 to location 350, 530.
You may recall that one of the files exported by TexturePacker was the class definition file which simply defined a constant value for each individual frame within the sprite sheet. This is where we use that constant. We could have just passed in the string value of the frame, however this approach is better as it ensures a compile time error is generated if we update the sprite sheet and forget to include this individual image file. The alternative is a run time error which might not occur until we have deployed to the device which could be a pain.

And that is pretty much all that you need in order to start rendering individual frames to the screen. It doesn’t matter if TexturePacker rotated these frames when the sprite sheet was produced or if the frames were trimmed etc – The code within the TexturePacker Loader takes care of all of this logic for us – We just need to specify (1) which frame we want to render and (2) where we want to position it!

So, now you know how to use TexturePacker, and you have an understanding of the TexturePacker Loader, you are now free to start integrating it with MonoGame!
However if you feel you aren’t quite ready to delve in yet, or maybe you want to see a more in depth example, then the next part of this tutorial is for you. Under the MonoGame heading below there are two sections – one for creating an iOS MonoGame application using Xamarin Studio – and one for creating a Windows 8 Store App using Visual Studio. They are quite similar – just choose the one that is appropriate for you. Or alternatively download an example MonoGame solution from Github showing how it is all put together.

MonoGame

For those that don’t know…

“…MonoGame is an Open Source implementation of the Microsoft XNA 4 Framework. The goal is to allow XNA developers on Xbox 360, Windows & Windows Phone to port their games to the iOS, Android, Mac OS X, Linux and Windows 8 Metro. PlayStation Mobile, Raspberry PI, and PlayStation 4 platforms are currently in progress…”

The above is pinched straight from the MonoGame website. Basically, it’s all about making cross platform game development easier. No need to learn different languages/APIs for different platforms. Instead just develop in c# for one platform – and then make (hopefully just minor) adjustments to run on other platforms.

In this tutorial I am going to show you how to create a simple demo Windows 8 Store app using the above sprite sheet to animate the ‘cap guy’ across the screen. This will be done using Visual Studio. I am then going to show you how to do exactly the same thing, using Xamarin Studio on a Mac, to create the same demo running on an iPad.

However, if you want to skip the below instructions and jump straight to the code then you can do so by grabbing the entire solution (Xamarin and VS solutions plus the TexturePacker sprites) from Github.

So, first up, Visual Studio…

MonoGame Windows Store Example with Visual Studio

Now, there are a couple of different approaches to getting MonoGame working with Visual Studio. Both are extremely easy – it just depends what your preference is….

One option is to download the windows installer for the latest release from MonoGame

This gives you a ‘MonoGame’ option in the list of templates presented when selecting to create a new project. As such you can choose the ‘MonoGame Windows Store Project’ and you’ll be up and running straight away…

Windows-MonoGame-CreateProject

An alternative approach (which I prefer as it is easier to update as new versions/updates of MonoGame become available) is to start a new standard windows store project and then install the monogame nuget package. The choice is yours!

Windows-MonoGame-Nuget

At this stage you should be able to build and run the solution and be presented with a ‘cornflower blue’ screen. If so then all is working!

The next step is to add our three TexturePacker files to the solution…

First, place the texture file and the data file into the Content folder of your solution and mark their ‘build action’ as ‘Content’.

Windows-MonoGame-DataFileProperties

This ensures that we can access these data files at run-time.

With regards to the SpriteNames.cs file (or whatever you decided to call it) this can go anywhere you like within your solution.

Next we need to bring in the TexturePackerLoader code that knows how to handle the TexturePacker data files – and render our sprites to the screen. This code is available in Nuget – so, right click on ‘references’ in your ‘solution explorer’ and select ‘Manage NuGet Packages’.

Windows-MonoGame-Loader-Nuget

Search for TexturePacker and install the package…

Windows-MonoGame-Loader-Nuget-Search

Most Nuget packages are a library DLL that just gets referenced into your project however, as described above, this Nuget package actually brings in the complete TexturePacker Loader source code.

TexturePackerLoader-ProjectFiles

Once we have our TexturePacker sprite sheet, data file, class file and the TexturePacker Loader source; we just need to start using it. So, at this stage I would suggest downloading the Demo package from Github.

Load up the solution and it should look something like below…

Windows-MonoGame-VisualStudio

Hit F5 and you should see the ‘Cap Guy’ walking backwards and forwards across the screen, which considering how little code there is, I think is pretty cool!

The next section explains how to create the same project using Xamarin Studio and targeting iOS. Then, for those who want to take a deeper look at this demo, there is a further section explaining a bit more about the Demo app.

MonoGame iPad Example with Xamarin Studio

There are probably a few different ways to get yourself setup to use MonoGame with Xamarin Studio, but my preference is to use the Nuget package. I prefer this as it is easier to update as new versions/updates of MonoGame become available.

So, load up Xamarin Studio and create a new iPad empty project as shown below…

Xamarin NewProject

From here select the Project \ Add Packages option…

Xamarin AboutToAddPackage

…and then search for MonoGame once the Nuget window appears…

Xamarin NugetPackageList

You will notice various different packages are available, including a couple of ‘official’ MonoGame ones. I would recommend installing the one highlighted – the ‘MonoGame’ package as this not only contains the binaries required to build against MonoGame, but also some sample code to get us up and running quickly.

Once installed then you’ll see a new ‘Packages’ folder appear in your solution with the MonoGame packages installed, as well as a couple of new source files – a Game1.cs and a GameMain.cs.

Xamarin AfterNugetAdded

Now there are two important steps that you need to take in order to run the solution at this stage.

First you must delete the AppDelegate.cs and Main.cs files, as these are replaced by the new Game1.cs and GameMain.cs files.

Secondly you must add a reference to the newly downloaded Nuget package. This is a little different to how it works in Visual Studio. So, right click on ‘references’ and select ‘edit references’ – you will be presented with a screen similar to below…

Xamarin AddReference

Select the ‘.Net Assembly’ tab and then browse to the MonoTouch folder within the MonoGame.Binares package – Click the MonoGame.Framework.dll – Click ‘Add’ – and then finally click ‘OK’.

You should now be able to run the solution and be presented with a ‘cornflower blue’ screen.

The next step is to add our TexturePacker files to the solution…

First, create a ‘Content’ folder and place inside it the texture and data files. Add them to the solution and ensure that the ‘build action’ for all of them is ‘BundleResource’ – This ensures that we can access these data files at run-time. The png files automatically get set this way, however the txt files may not.

Notice how we have two sets of similarly named files in the Content folder – one with the @2x extension which will be used for Retina tablets – and one without which will be used for non-retina tablets. This is handled for you – you do not need to do anything special within the code.

Xamarin ContentProperties

With regards to the SpriteNames.cs file (or whatever you decided to call it) this can go anywhere you like within your solution.

Next we need to bring in the TexturePackerLoader code that knows how to handle the TexturePacker data files – and render our sprites to the screen. This code is available in Nuget – so, select Project / Add Packages and this time search for TexturePacker and install the package…

Xamarin NugetTexturePacker

Most Nuget packages are a library DLL that just gets referenced into your project however, as described above, this Nuget package actually brings in the complete TexturePacker Loader source code.

Xamarin TexturePackerReferences

Once we have our TexturePacker sprite sheets, data files, class file and the TexturePacker Loader source; we just need to start using it. So, at this stage I would suggest downloading the Demo package from here.

Load up the solution and it should look something like below…

Xamarin FullSolution

Click the ‘run triangle’ and you should see the ‘Cap Guy’ walking backwards and forwards across the screen.

If you want a deeper look at this demo code then the following section goes into a bit more depth.

DemoGame

Well done for getting this far. I hope the above has been useful!
This final section isn’t really about TexturePacker or MonoGame – It is just a brief overview of some of the other classes in the demo app which you might find useful for your own projects – and if so then are free to use.

Hopefully most, if not all, of the code in the DemoGame class is self explanatory. The interaction with the TexturePacker Loader code has already been explained above. However you may notice the InitialiseAnimationManager() method. This method defines how the ‘Cap Guy’ should be animated within the demo.

The first part of this method defines where he should first be positioned on screen and the speed at which he should move (and if running under iOS then this can be effected by the scale of the device (i.e. is it a retina device or not).

Code-DemoGame-Position

Next you’ll see two local variables created which are simply arrays of frame names. These simply define which frames make up an individual sequence of movement. i.e. turnSprites is an ordered array of all the frames required to animate Cap Guy turning, whilst walkSprites is an ordered array of all the frames required to animate Cap Guy walking.

Code-DemoGame-TurnSprites

Along with the above sequence of frames, we can state the velocity of the Cap Guy, time before switching frames and whether the frames should be flipped (e.g. walking left as opposed to walking right). Together this information is enough to define an individual animation – as declared in code like so…

Code-DemoGame-Animations

Now that we have defined each animation type – walking left, walking right, turning left to right and turning right to left; we can join these animations together to make our entire looping animation of the Cap Guy walking backwards and forwards across the screen.

Code-DemoGame-Animations2

i.e. He will complete the ‘walk right’ animation six times, turn around, complete the ‘walk left’ animation six times and then turn around again.

Finally we create an instance of the AnimationManager class passing in all of this information.

Code-DemoGame-AnimationManager

Once this is defined, all we need to do is call the AnimationManager’s update method each game loop.

Code-DemoGame-Update

…and then ensure we use the information from the AnimationManager class to ensure the correct image, with the correct sprite effects (whether flipped or not) is rendered to the correct position in our Draw method…

Code-DemoGame-Draw

For your own games you may want to implement your own way of handling the animation – but, if not, then you are more than welcome to use the code from above!

The End

I hope this tutorial has been useful. Let me know how you get on!

For those who’ve skipped straight to the end without building the demo, here is a video of our demo running in the iOS simulator via Xamarin Studio.

At some point in the future the intension is to also publish the TexturePacker Loader to the Xamarin Component Store. Once that is done then I’ll post an update to the blog!

Links related to this tutorial

MonoGame
TexturePacker
Github Demo Source Code