Animating Sprites with Sprite Kit

With Sprite Kit it is possible to create sprite animations rather easily. To run an animation action, you load in a list of images, called textures. Next, you swap the texture with a different one at runtime. In this tutorial we will create a sprite and add an animation action to it, so it appears the sprite is in movement.

Open Xcode and create a new SpriteKit Game. For product name, use SpriteAnimationTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices.

First we remove some code from the Sprite Kit template. In the initWithSize method from myScene.m remove all code inside the if(self = [superinitWithSize:size]) block. Also remove the touchesBegan:withEvent method. Next we will need some texture image for the animation, so you can download these images of a robot, unzip the file and add the images to the project. 

Add the following properties to the @interface section of the scene.m file.

@interface MyScene()

@property (nonatomic,strong) SKAction *spriteAnimation;
@property (nonatomic, strong) SKSpriteNode *sprite;


In the initWith Size method add the following lines beneath the if (self = ....) line

self.scene.backgroundColor = [UIColor whiteColor];

self.sprite = [SKSpriteNode spriteNodeWithImageNamed:@"robot1.png"];
self.sprite.position = CGPointMake(self.size.width/2, self.size.height/2);

[self addChild:self.sprite];

We have made the background of our scene white and positioned our robot to the center of the scene. Add the following lines just beneath the previous code

NSMutableArray *textures = [NSMutableArray arrayWithCapacity:4];

for (int i = 1; i < 5; i++)
NSString *textureName = [NSString stringWithFormat:@"robot%d", i];
SKTexture *texture =
[SKTexture textureWithImageNamed:textureName];
[textures addObject:texture];

We have created an array of textures, containing each texture image of the robot. Next, we will create the animation.

self.spriteAnimation = [SKAction animateWithTextures:textures timePerFrame:0.2];

SKAction *repeat = [SKAction repeatActionForever:self.spriteAnimation];
[self.sprite runAction:repeat];

The animatiWithTextures:timePerFrame loads in the textures array and this action os inserted into the repeatActionForever method. Next, our repeatAction is added to our sprite. Build and Run, you should see the robot walking.

You can download the source code of the SpriteAnimationTutorial at the ioscreator repository on github.