Back in Part 3 of this SpriteKit/Swift tutorial series we looked at loading game sprites using a texture atlas and implemented a simple animation system. At the time I said this wasn’t the way you perform animation and that I would cover the proper way later. Then in Part 4 we covered SpriteKit actions showing how to perform a number of different actions. Now we look to combine the two, using actions to perform sprite sheet based animations using a TextureAtlas.
This example is basically a perfect mash-up of the prior two tutorials, so it will be code heavy and explanation light. So, on to the code!
import SpriteKit
class GameScene: SKScene {
let textureAtlas = SKTextureAtlas(named:“jet.atlas”)
var spriteArray = Array<SKTexture>();
var monsterSprite = SKSpriteNode();
override func didMoveToView(view: SKView) {
view.scene!.anchorPoint = CGPoint(x: 0.5,y: 0.5)
spriteArray.append(textureAtlas.textureNamed(“sprite1”));
spriteArray.append(textureAtlas.textureNamed(“sprite2”));
spriteArray.append(textureAtlas.textureNamed(“sprite3”));
spriteArray.append(textureAtlas.textureNamed(“sprite4”));
spriteArray.append(textureAtlas.textureNamed(“sprite5”));
spriteArray.append(textureAtlas.textureNamed(“sprite6”));
monsterSprite = SKSpriteNode(texture:spriteArray[0]);
monsterSprite.position = CGPoint(x:-view.bounds.width/2, y:0)
monsterSprite.xScale = 2;
monsterSprite.yScale = 2;
addChild(self.monsterSprite);
let animateAction = SKAction.animateWithTextures(self.spriteArray, timePerFrame: 0.20);
let moveAction = SKAction.moveBy(CGVector(view.bounds.width,0), duration: 1.4);
let group = SKAction.group([ animateAction,moveAction]);
let repeatAction = SKAction.repeatActionForever(group);
self.monsterSprite.runAction(repeatAction);
}
override func update(currentTime: NSTimeInterval) {
if(monsterSprite.position.x > self.view.bounds.width/2){
monsterSprite.position.x = –self.view.bounds.width/2;
}
}
}
And when you run it:
Basically we create our texture atlas like we did before, but instead of creating individual SKSpriteNodes using the atlas, we instead create an array of SKTextures. We then pass that array of textures, representing each animation frame, to the action animateWithTexture. The parameter timePerFrame represents how long each individual frame will be shown. The rest is just a couple more SKActions to make things interesting. One to move the sprite from the left to the right, one to group the texture animation and move action together, then another action to repeat it forever.
As you can see, between TextureAtlas and animateWithTexture, creating animations in SpriteKit is pretty easy.