1

Under the SKSpriteNode class, you can do the following to animate an object

private func animate(){
  var playerTextures:[SKTexture] = []
  for i in 1...3 {
    playerTextures.append(SKTexture(imageNamed: "image00\(i)"))
  }
  let playerAnimation = SKAction.repeatActionForever(
    SKAction.animateWithTextures(playerTextures, timePerFrame: 0.1))
  self.runAction(playerAnimation)
}

The above code can animate an object using the sequence of images. Here the image files would be image001.png image002.png image003.png

Here come's my question, how can I animate images if the file names are image001.png image002.png ... image009.png image010.png image011.png image012.png The key point here is the problem with the zero paddings. Any ideas?

Clinton Lam
  • 687
  • 1
  • 8
  • 27

1 Answers1

2

Assuming you will only have three digits number you could add your pictures that way:

for i in 1...3 {
    let imageNumber = String(format: "%03d", i)
    playerTextures.append(SKTexture(imageNamed: "image\(imageNumber)"))
}

This will give you image001, image002 and image003

This requires that you import Foundation at the beginning of your swift file

The Tom
  • 2,790
  • 6
  • 29
  • 33
  • thanks, btw, you may have a typo "image\(String(format: "%03d", i))" – Clinton Lam Feb 18 '16 at 14:01
  • I edited my answer, I think it should be okay now and easier to read ;) – The Tom Feb 18 '16 at 14:06
  • Please note that the preferred way of saying 'thanks' around here is by up-voting good questions and helpful answers (once you have enough reputation to do so), and by accepting the most helpful answer to any question you ask (which also gives you a small boost to your reputation). Please see the [About] page and also [How do I ask questions here?](http://stackoverflow.com/help/how-to-ask) – The Tom Feb 18 '16 at 14:08