Using a Texture Atlas with Xamarin
Recently I have been doing some work in SpriteKit with Xamarin. I have used Xamarin and its previous incarnations for 5 or so years however I am very new to the world of 2D gaming and SpriteKit.
In prototyping ideas, I came across the need for using textures within an app to improve performance of animation. One way to achieve this is via creating a Texture Atlas. I found plenty of examples with XCode however not so many with Xamarin.
First lets create a new Xamarin Sprite Kit Project.
I have a few images here that I from a recent project, just a telephone that rings.
Add a folder into the project with the .atlas suffix, e.g. MyAwesomeAnimation.atlas. This will contain all images that should be converted into an animation. In this example, I have a telephone with 7 images.
Given I have used the File -> New SpriteKit Project
in Xamarin Studio, I will just remove the implementation in the MyScene
class and replace with the following.
Firstly in the constructor, create the texture atlas. By convention, the name of the atlas matches the folder in the app.
telephones = SKTextureAtlas.FromName ("Telephone");
Then, to illustrate a simple implementation, when the app is touched, show the animation.
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
foreach (var touch in touches) {
#Get the location and create a sprite to animate
var touchLocation = ((UITouch)touch).LocationInNode (this);
var telephoneSprite = new SKSpriteNode ("Telephone_1");
telephoneSprite.Position = touchLocation;
#A little awkward, however get the list of image names to then index into the atas
var telephoneList = telephones.TextureNames
.Select (x => telephones.TextureNamed (x))
.ToArray();
var animationAction = SKAction.AnimateWithTextures (telephoneList, 0.05);
telephoneSprite.RunAction(SKAction.RepeatActionForever(animationAction));
AddChild (telephoneSprite);
}
}
The simple example is available at https://github.com/merbla/SpriteKitAdventures