Animated Sprites for SpriteKit and Swift with TexturePacker

This is part of a free course that teaches game design and the Swift programming language. It contains examples from a real game I created called ForeverMaze. The full course includes the source code for the whole game.

This article will show you how to create sprite sheets and load them into your SpriteKit game with Swift. It includes source code that makes the whole process painless.

In 2D games you generally will have one or more “sprites,” which are simply images that represent an object. This becomes a bit tricky when you have multiple frames of animation and multiple cardinal directions. For example, in a 2.5 game, a character can be either idle or walking (animation) in any of four directions (north, west, east, south).

Download Animation.swift

Download Direction.swift

Halving Our Work

Hero facing SouthBefore we start, let’s recognize a simple fact: we only need half the artwork.

The “hero” sprite to the right is facing South. But if we flip it along the X-axis, he is suddenly facing East. Since we can do X-Axis transformations in Swift, we can actually get away with only creating art for two of the four cardinal directions.

This handy trick will save us memory, disk space, and programming time. The Direction.swift class is just a simple enum that defines the four directions.

It contains a handy helper that converts degrees into a direction. This is useful for when we create the D-Pad style control, later on. It will let us determine what direction the player wants to move based upon the position of his thumb.

Using TexturePacker to Create a Sprite Sheet

TexturePacker is a great tool for creating sprite sheets that work in SpriteKit (and most other game engines). It will cost you a few dollars, but is well worth it. Check out my TexturePacker settings to see how to create your sprite sheet:

TexturePacker SpriteKit settings

Naming is important! The Animation class expects that the images named like they are here. First comes the asset name (like “hero”), then the action (“idle” or “walking”), and finally the frame number in the sequence.

You can also run the exported png files through a png compression tool, like TinyPng.com, to keep file size down.

Loading Up a Sprite Sheet in Swift

The following code belongs to a GameObject class. When you call the draw()  function, it first loads the asset’s sprite sheet and then pulls out the correct animation. If you change the direction property, the sprite is automatically updated to reflect the new state.

  private let assetName = "hero"
  private var currentAnimationKey = ""
  private var sprite = SKSpriteNode()
  private var direction = Direction.S

  func draw() -> Promise<Void> {
    return Animation.preload(assetName).then { (animation) -> Void in
      self.currentAnimationKey = ""
      self.loadCurrentTexture()
    }
  }

  var currentTexture:SKTexture {
    return self.animation!.getTexture(.Idle, direction: self.direction)
  }
  
  var animation:Animation? {
    return Animation.cache[assetName]
  }
  
  var speed:Double {
    return 1
  }
  
  private var isReversedAnimation:Bool {
    return self.direction == .E || self.direction == .W
  }
  
  func loadCurrentTexture() {
    self.sprite.xScale = 1
    self.sprite.yScale = 1
    self.sprite.texture = self.currentTexture
    self.sprite.size = self.sprite.texture!.size()
    self.updateAnimation(.Idle)
  }
  
  func updateAnimation(group: AnimationGroup) {
    guard self.animation != nil else {
      return
    }
    let key = animation!.getKey(group, direction: direction)
    if key != currentAnimationKey {
      currentAnimationKey = key
      self.sprite.removeActionForKey(Animation.actionKey)
      self.sprite.runAction(self.animation!.getAction(group, direction: direction, speed: self.speed), withKey: Animation.actionKey)
    }
    self.sprite.xScale = isReversedAnimation ? -1 : 1
  }
  
  
  var direction:Direction {
    didSet {
      self.updateAnimation()
    }
  }

 

 

If you enjoyed this post, why not enroll in the free course? It contains hours of video content, source code downloads, examples and more. I cover many different intermediate and advanced topics for creating a real-time game in Swift with SpriteKit and Firebase. You can check out the complete game at ForeverMaze.com.

[author]

Leave A Comment

You must be logged in to post a comment.

Back to Top