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.


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…


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


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…


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.


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.


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.


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…


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…


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


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.


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.


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…


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…


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


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.


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…


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!


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’.


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’.


Search for TexturePacker and install the package…


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.


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…


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.


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).


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.


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…


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.


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.


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


…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…


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

Code And Web tutorial
Github Demo Source Code

DDD East Anglia

Yesterday I presented at the DDDEA conference in Cambridge. I talked about MonoGame and presented a couple of demos – one a live port of an iPad demo to Windows8 – and one including an example of how to create animation in MonoGame with the help of Spine by Esoteric Software.

I hope everyone who attended enjoyed the presentation!

At the end of the presentation I had a slide with a load of links to the various things I talked about. As promised in the talk I have put those links here for peoples reference….

MonoGame Source:
Dancing Crab Demo Source:
Chase Camera Demo Source:
My Paint Replay App:

Dragons and Dancing Crabs [An update]

Just a quick blog post to update the situation with the Esoteric Software runtimes. As of today the official Generic C# and XNA runtimes have been made available by Esoteric Software. As such there is no need for my runtime anymore. This is good news as it means that any new features added by Esoteric Software will be automatically fed through to the official run-times. I have therefore updated my GitHub Repository to use the official runtimes. As such there is a lot less code to see! If you still want to get hold of ‘my old cobbled together code’ – converted from the corona and java runtimes – then I’ve tagged the tree on the master branch at the point before I removed the runtime – Tag name is PreOfficialRuntime.

One thing to note is that the format of the atlas (Sprite Sheet) files have changed (compared to my runtime) as a result of moving to the official run-times. If using TexturePacker then you should export the “LibGDX” format rather than the Json formats.

I found one small issue with the runtime when importing skeleton Json files with slot changes in the animation, however by the time you read this it’ll be fixed because I can see my pull request has already been accepted! Fast work from the team at Esoteric!

I did find one more issue, that is not yet resolved, where the graphics are distorted when the iPad is rotated. I haven’t yet found where this issue lies. I wonder if it is with the custom SpriteBatcher code in the XNA runtime, however it may just as likely (more likely) be something I’ve done wrong! I’ll see if I can look into this over the next few days and fix it up.

[Edit: 12-04-2013 – The rotation distortion is now fixed. Esoteric Software fixed an issue in the XNA runtime] 🙂

Dragons and Dancing Crabs

Creating smooth animations in MonoGame using Spine

For those of you who don’t want to read the entire blog post (shame on you), here’s a slightly slowed down video of some animation in MonoGame using Spine to create the animation. In summary, this can be achieved with just a few lines of code in MonoGame.


This blog post is a guide to producing smooth animation in MonoGame using Inkscape, TexturePacker and Spine. Below is a ‘short and simple beginner level’ introduction to each of these apps and then a slightly more detailed step by step tutorial for getting an animation up and running in MonoGame.


Inkscape is an Open Source scalable vector graphics editor – similar to Illustrator or CorelDraw, but completely free of charge. You don’t need to be pay loads of money to produce good vector graphics, but you do need to be able to draw. If you can’t draw then it doesn’t matter how much money you spend on an app, it won’t make you suddenly produce better graphics.
I hadn’t used any vector graphics editing software before so Inkscape seemed a good choice – it was free so if I didn’t get on with vector graphics editing then I hadn’t wasted any money.


TexturePacker is a neat tool for producing ‘sprite sheets’. Once you’ve created all your separate image files for your game (e.g. using Inkscape), you simply drag and drop them into TexturePacker which then exports one large image file along with a data file describing where each individual image is within the larger image. Using sprite sheet is more efficient than loading lots of individual images in game development. (See Wikipedia for more info).


Approximately a month ago I heard about a Kickstarter project from Esoteric Software to make Spine – an application that allows you to make 2D skeletal animation for games. Taken from their web-site…

“…Spine replaces traditional raster animation in games, providing smoother animations that are easier to produce. Animations can be created without needing more art and are so tiny that games can make extensive use of them…

So I backed the project and now have a working copy of the Spine app running on my mac – and it is pretty good! In my opinion anyone who needs to animate any kind of character (or title screen for that matter) should buy it. It will save you so much time! Note: Spine is also available for windows.


MonoGame is an Open Source implementation of the Microsoft XNA 4 Framework. As a MonoGame Evangelist’ I will be biased of course, however even so, it is awesome! 🙂 Develop an app using MonoGame and with a few device specific changes you can target lots of different platforms with a huge percentage of shared code.


That’s the introduction out the way, so let’s start creating our animation!
Note: All the code and graphics are available on github.

Step 1 – Inkscape – Creating our graphics

I decided to try out a vector based graphics application for my next game so that it would be easier to produce graphics for various screen sizes (e.g. iPad v iPad retina). i.e. I could just draw one set of graphics and then scale the vector diagram appropriately before exporting the png/jpg file.

Note: You don’t have to use a vector graphics editor for producing your images to use in Spine or MonoGame. Any graphics tool that produces images is fine. I simply wanted to try out a vector graphics editor, as I hadn’t used one before.

If you haven’t used Inkscape before then I’d recommend you follow the tutorials in the first few chapters here. It’s fair to say that Inkscape is pretty powerful, but if creating vector graphics is new to you then you will have to put some effort in to avoid frustration. I also found that the 2D Game Art for Programmers site was a useful learning resource.

So traditionally when creating graphics you might have an image of your character in one position and then another image in the next position and so on – e.g. one image with both feet together – another with left foot forward and then one with the right foot forward. This is fine, however it would be nice to make animations where each limb moved smoothly – hence this tutorial.

One of the main characters in my next game is going to be a crab, so I’ve drawn a simple crab, as below, using Inkscape.


Now, rather than exporting this entire picture as a single image, I have exported each ‘movable part’ as separate images – The intention being that we want to animate each body part separately to create realistic motion – hence we need separate body part images. Fortunately Inkscape allows you to export individual shapes/paths of an image to a bitmap/png/etc file – as shown below.


The only problem however is that it actually exports the square selection surrounding all selected images rather than the actual selection – therefore you need to move the selected body part to a blank section of the page, then export the selection and then undo the move so that it goes back to the correct location. Repeat this for each body part and you will end up with a series of images files – one for each movable body part.
Note, it is worth giving some thought to how you name your images files to make it easier to identify them later – e.g. BackUpperLegLeft.

Step 2 – TexturePacker

Now we have all our individual images files we need to load them into TexturePacker to create our Sprite Sheet. This part is very easy.

  • Open TexturePacker
  • Drag and drop each individual image file into TexturePacker
  • Ensure the Data Format is set to “JSON (Array)”
  • Ensure “Trim Mode” is set to ‘none’
  • Press Publish to create a Json data file and a PNG Sprite Sheet

You should now end up with a Json file looking something like this…

{"frames": [

	"filename": "BackLowerLegLeft.png",
	"frame": {"x":294,"y":335,"w":36,"h":69},
	"rotated": false,
	"trimmed": false,
	"spriteSourceSize": {"x":0,"y":0,"w":36,"h":69},
	"sourceSize": {"w":36,"h":69}
	"filename": "BackLowerLegRight.png",
	"frame": {"x":285,"y":407,"w":36,"h":69},
	"rotated": false,
	"trimmed": false,
	"spriteSourceSize": {"x":0,"y":0,"w":36,"h":69},
	"sourceSize": {"w":36,"h":69}

…and a SpriteSheet looking something like this…


Step 3 – Spine

Right, we’ve done the easy bit – now for the fun part! Creating our animation…

At this point I would suggest you go to the Esoteric Software web-site and watch the “Quick Overview Part 1” and “Quick Overview Part 2” videos. They are both approximately 10 minutes in length. They will tell you enough for you to create an animation in Spine. But in summary, you will need to export a copy of the entire crab from Inkscape and import this as your template image in Spine so you can line everything up – then draw the ‘bone structure’ on top of this template – then apply the individual images to each bone – delete the original template file and then you can start creating an animation by rotating each bone/image on various frames of the timeline. Spine will then take care of ensuring a smooth animation between each frame. Below we can see the ‘bone structure’ I have created for the crab.


One thing you may notice is that there are ‘bones’ for the two eyes and eye-lids. The reason for this is that I am going to make the eye and eye-lid jump up in the air in a cartoon style. So, don’t necessarily think of ‘bones’ as having to mirror where real bones are – instead it is all about what parts of the animation need to move. Further to this, if I had wanted the teeth to move about then one approach would be to create separate teeth images instead of them being part of the head image – then I could have created ‘bones’ to attach them to and animated them.

Something else you may have noticed earlier is the additional eyes in the Sprite Sheet exported by TexturePacker. We have one set for looking forwards, where the pupil is in the middle of the eye – and another set for looking to the side where the pupil is on the side of the eye. The reason for this is because we can still use ‘old fashioned style’ animation where required – i.e. When creating our crab skeleton in Spine we can attach both types of eye images to the ‘eye bone’ but choose on a per frame basis which one we want to use. Thus, when the crab walks to the side he can look to the side, but when he is stood still he can look forwards.

Once you’ve completed your animation within Spine you’ll need to export a Json file of your work. (Select the ‘export’ menu option – ensure Json is the selected data format – select a destination – and press ‘Export’. This will create a Json file containing the basic skeleton structure of your character and all the animations.

Step 4 – Putting it all together

At this stage we have the following…

  • Our Sprite Sheet [produced by TexturePacker]
  • A Json file describing the details of the individual images within the Sprite Sheet [produced by TexturePacker]
  • A Json skeleton file [produced by Spine]

We now need to work out how to put this all together to create animations within MonoGame…

On the face of it this may sound quite tricky. Although writing code to import the Sprite Sheet and parse the Sprite Sheet Json data file is relatively simple, writing code to import the Spine animation data and then understand that data to perform the animation is quite complex. Fortunately Spine offers more than creating the animation – The guys at Esoteric Software have also created some run-times for different platforms which you can plug into your own code. They have a runtime for LIBGDX (in java) and another for Corona (in LUA).

But wait, how does that help us? We need a c# MonoGame runtime.

Now, one of the stretch goals for the Spine Kickstarter was to develop a generic c# runtime. The good news is that this stretch goal has been reached and is due to be developed within the next few weeks, however I couldn’t wait that long so I decided to try writing my own runtime specifically for MonoGame. 🙂
Now, I must point out that although I do indeed have a runtime which is available for anyone to use, I don’t really feel I can take a huge amount of credit for it because it is entirely based upon the work already done by the guys at Esoteric Software – i.e. heavily based on the LIBGDX and Corona runtimes.

So, the source code for the MonoGame runtime can be found on GitHub. Grab a copy of this and you will see a ‘runtime project’ and an iOS ‘demo project’. Add a reference to MonoGame and it will build and you’ll see an animated crab.
Note: If you want to run this on a different platform than iOS then just create a new runtime project (for your platform) and add all the source files. Then implement an equivalent demo project.

If we look at the code needed to create an animation then it is pretty simple! Below is our entire Game class for rendering a smooth animation. The key parts are…

  • The LoadContent method where we (a) load our TexturePacker SpriteSheet and (b) load our Spine skeleton Json file.
  • The Draw method where we move the animation along based on the time and then simply call ‘Draw’ on the skeleton passing in our SpriteBatch and letting the Spine runtime take care of the rendering.


/// <summary>
/// Animation demo.
/// 2013-March
/// </summary>
namespace Demo
	using Microsoft.Xna.Framework;
	using Microsoft.Xna.Framework.Graphics;
	using Microsoft.Xna.Framework.Input.Touch;
	using Spine.Runtime.MonoGame;
	using Spine.Runtime.MonoGame.Attachments;
	using Spine.Runtime.MonoGame.Graphics;
	using Spine.Runtime.MonoGame.Json;

	public class AnimationDemo : Game
		private readonly GraphicsDeviceManager graphicsDeviceManager;
		private SpriteBatch spriteBatch;
		private Texture2D crabTextureMap;
		private Skeleton crabSkeleton;
		private Animation crabAnimationWalk;
		private float timer = 0;

		public AnimationDemo ()
			this.graphicsDeviceManager = new GraphicsDeviceManager (this);
			this.graphicsDeviceManager.IsFullScreen = true;
			this.graphicsDeviceManager.SupportedOrientations = 
				DisplayOrientation.LandscapeLeft | 
					DisplayOrientation.LandscapeRight |
					DisplayOrientation.PortraitDown | 
			this.Content.RootDirectory = "Content";
		protected override void Initialize ()
			TouchPanel.EnabledGestures = GestureType.Tap;
			base.Initialize ();

		protected override void LoadContent ()
			// Load our sprite sheet
			this.crabTextureMap = Content.Load<Texture2D>("crab.png");
			var texturePackerReader = new TextureMapJsonReader ();			
			var spriteSheet = texturePackerReader.ReadTextureJsonFile("Content/crab.json", this.crabTextureMap);

			// Load our basic skeleton
			var skeletonReader = new SkeletonJsonReader(new TextureAtlasAttachmentLoader( spriteSheet));
			this.crabSkeleton = skeletonReader.ReadSkeletonJsonFile("Content/crab-skeleton.json");
			this.crabSkeleton.FlipY = true; // MonoGame origin is top left so we need to flip the y axis

			this.crabAnimationWalk = crabSkeleton.Data.FindAnimation ("WalkLeft");

			// Finally set the initial state/position of our crab
			var root = crabSkeleton.GetRootBone();
			root.X = 500;
			root.Y = 750;

			this.spriteBatch = new SpriteBatch (this.graphicsDeviceManager.GraphicsDevice);

			base.LoadContent ();

		protected override void Draw (GameTime gameTime)
			this.spriteBatch.Begin ();

			this.GraphicsDevice.Clear (Color.CornflowerBlue);

			// In reality you'd probably pass in some time related variable to this rather than
			// my crude timer variable for demonstration purposes.
			// Also you'd probably want to perform the UpdateWorldTransform outside of the draw method
			// Should probably be in the Update method
			this.crabAnimationWalk.Apply(crabSkeleton, timer++ / 100, true);

			this.spriteBatch.End ();

			base.Draw (gameTime);

		protected override void Dispose (bool disposing)
			this.crabTextureMap.Dispose ();

			base.Dispose (disposing);

If you want to see this running on your machine then you can grab the source code from GitHub.

Where do we go from here…

Currently the structure of the MonoGame runtime code needs a bit of work. As stated, I cobbled it together by looking at the existing Corona and LIBGDX runtimes and just concentrated on getting something working. The code could do with a bit of refactoring in terms of encapsulation and general c# structure, however it works so it will do for now. There are probably a couple of features not yet implemented (colour blending for example) and I haven’t tried the mixing of animations or different skins yet. Also I believe you can export binary data, rather than Json, from Spine which will probably load quicker – however I haven’t written a binary importer yet.
I suspect I will actually wait until the official generic c# runtime is released and then fork that to create the next version of the MonoGame runtime. The advantage of this is that the core of the code will then be provided by Esoteric Software so any new features or bug fixes can just be taken from their fork – and I would imagine my MonoGame part of the code will be much smaller. However, it is a bit of an unknown at this stage – until the generic c# runtime is available we won’t know how well a MonoGame implementation might fit in – so worse case scenario is that I decide to keep my existing MonoGame runtime and maintain it. Either way, we can be sure that Spine animations will work with MonoGame!

At this point I feel I should also point out another option available to people. Trugnt has taken a fork of MonoGame and implemented loads of LIBGDX features within it. Their source is available on GitHub so gives people another option when it comes to implementing Spine and MonoGame together.

Enough with this crazy crab! Where’s the dragon?

Yes, there is a rather cool dragon in the video at the top of the page. If you want to see the graphics and Json files for that then you’ll need to download Spine from Esoteric Software and try them out yourself 🙂 Those graphics aren’t mine so I didn’t feel it was appropriate to include them in my demo project on GitHub. Consider it an exercise for the reader 🙂


So, in summary, if you want to create smooth animations for your games then I’d strongly recommend taking a look at Spine. I love it!
And if you use MonoGame to create your games then you now have the ability to use those animations in your MonoGame apps!

I hope this has been useful to you. Let me know how you get on.
Good luck and have fun!

EDIT: 04/04/2013 – Updated blog entry slightly to reflect recent change to the runtime as a result of a data format change in the latest version of Spine. The animation data is now included in the main skeleton Json file.

EDIT: 11/04/2013 – This is slightly out of date now because the official c# runtime has been produced by EsotericSoftware. See later blog post for more information.

I’m in the App Store! Woohoo!

Paint Replay

So, my new years resolution at the beginning of 2012 was to release an app into the app-store. In the end I was one month late, however that’s good enough for me!
Paint Replay is now in the App Store – running on the iPad – just search for ‘Paint Replay’. Now let me just say, if you are looking for some awesome, all singing, all dancing paint application then this is not it – it’s just a simple paint app – but it is free and contains no ads.



  • MonoGame is awesome – Everyone should use it for all games from this point onwards!
  • MonoDevelop from Xamarin is awesome
  • A bit of history

    So, approximately 15 months ago I bought a Mac, downloaded a copy of MonoDevelop and decided I wanted to release a game into the App Store. MonoDevelop was perfect as it meant I could program in c# (which is what I do every work day anyway) and I had no intention of learning objective-c – life is too short!
    I then heard about MonoGame – a way of writing something (in c#) that could potentially run on ‘any’ platform – that sounded kind of cool so I thought I’d give it a go. The timing was perfect as I was just learning about Git – and the MonoGame source was hosted on GitHub.
    Anyway, to cut a long story short, I decided to write a simple proof of concept Paint application using MonoGame before diving into developing a game. I developed enough of the app in order to create a simple picture, and then posted a time-lapse video of the picture being created to YouTube…

    I was actually going to leave it at that and start looking at writing a game, however the good folks at Xamarin persuaded me to complete the Paint app.

    Now, here we are some months later and it is in the App Store – and so this blog post gives a small glimpse of how I achieved that and the sort of problems I encountered along the way…

    Why did it take so long?

    First thing to say is that (like everything) it took a lot longer than I first anticipated, however looking back on it this should not have surprised me. I wasn’t working on this 9-5 in the office – this was a ‘in my spare time’ hobby – An odd evening here and there – indeed in the summer I think I didn’t do anything for a couple of months as I was busy enjoying the lighter evenings with the family etc. It would have been interesting to have kept track of how much time I spent on the various aspects of the development – coding – graphics – etc – certainly something I will do for future projects.
    One of the problems with working on something part time in the evenings is that you kind of forget where you are from one day to the next – this invariably means it takes even more time. Also I feel that the quality of my code probably wasn’t the best – by the end of the day you are feeling more tired.

    Mission Creep!
    It is all too easy to add some great new feature to the development list. We’ve all suffered from this – however in this instance I only have myself to blame. With my next project I’ll certainly be establishing early on what should be in the first release and have clear estimates and goals. It’s what we do in ‘real life’ so why should it be different for pet projects!


    So, let’s talk about MonoGame…

    Well, this is taken from the web-site and pretty much sums it up…

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

    Imagine writing a game for one platform and then easily porting it to another. If you know nothing about MonoGame then I suggest you head over to their web-site now and take a look at some of the amazing games that have been ported from one platform to another – Massive titles “Draw a Stickman” and “Bastion” are available on at least 4 different platforms by sharing huge amounts of source code between the different platform versions.

    Now, I’ve only released my simple Paint Replay app on to the Apple store, but potentially a lot of the code could be re-used/ shared in order to publish it to other platforms.

    Anyway, I digress…

    So, I was developing my Paint app using MonoGame when I hit upon a problem. I was trying to call a method that threw a NotImplementedException. This was a big problem!
    However, it actually worked out quite well because it meant that I dived into the MonoGame source – implemented the missing method and submitted a pull request. It was accepted and then everything was fine!
    Of course I make it sound much simpler that it was!
    At the time my knowledge of Git was not as it is today – suffice to say that I well and truly screwed up my initial attempt at the pull request. Fortunately the MonoGame guys were extremely understanding and helpful and I eventually submitted it correctly. The great thing here is that this had the side effect of improving my understanding of Git.

    iOS updates

    If you’ve downloaded my app then you may have noticed that it requires at least iOS6. This isn’t because of some new feature in iOS6 that I’m making use of. The problem I found is that the iPad rotation logic seemed to change with iOS6, which meant that my app did not rotate properly. I was almost at the stage of limiting the app to just work in landscape mode, however I eventually managed to resolve the issue – but the problem was that I had no way of knowing whether my ‘fix’ would break the app when running under iOS5 or earlier versions. I therefore set the minimum version of the app to iOS6. I’m guessing that there must be some way in MonoDevelop / xcode etc to set the iOS version that you wish to test the app under however I wasn’t sure. [As it happens I believe I do now know how to do this – something for me to try… Stack Overflow]

    App Submission

    Once the app was complete it was time to submit it to Apple – this was the bit I was most apprehensive about. Would they come back to me with a big list of things that needed changing? Or worst still, just say ‘no’. As it happens this went extremely smoothly! 6 days after submitting my app I received an email stating that it was available for download!


    If I can do it then so can you!

    If you find yourself reading this blog and are thinking about developing a game then I would strongly recommend using MonoGame – it’s awesome and it’s run by a great bunch of people!
    The main MonoGame web-site is – this has links to the discussion groups/ forums and also to the source code on Github (which is free to use).
    If you intend to develop for the iPad/ iPhone then you’ll need to do so on the Mac using MonoDevelop (with MonoTouch) from Xamarin. The free version of MonoDevelop / MonoTouch is fantastic – A fully functional rich IDE that lets you run your app in the iOS simulator. Eventually you’ll want to run your app on real hardware and of course publish it to the App Store at which point you’ll need to buy a license for MonoTouch and purchase an Apple Developer license (although I’d recommend that if you are looking to develop something for iOS that you actually get a license and test your app on real hardware way before you get to the point of deciding to publish it – The simulator is great but there is no substitute for testing on the real thing!). MonoTouch can be found here.

    So what next?

    So, next I intend to develop a game of some kind. Probably something small to start with, however it will definitely be using MonoGame! And I intend to use TDD from the outset.

    If anyone is interested in looking at the source code for Paint Replay then it is on GitHub.

    The web page all about Paint Replay is here.

    Bye bye for now…

    [EDIT: BTW – I’ve only ever tested this on an iPad 2. It should work on iPad mini, iPad 1 and an iPad retina. If anyone does have problems then leave a comment and let me know (or indeed let me know if it works fine – that would be great).]

    MonogameLogo1920x1920 xamarin