Sprite Kit Animations and Texture Atlases in Swift 4

1.1k views Asked by At

Currently working on an application that requires a little bit of animations through an array of images. I've done tons of research online on how to resolve my issue but couldn't run into anything for Swift 4. Below is my code, it shows the first picture in the loop when I run the app but no animation at all. Everything looks fine, I don't see a problem with my code but maybe you guys can help. Appreciate it in advanced!

let atlas = SKTextureAtlas(named: “mypic”)
var TextureArray = [SKTexture]()
var person = SKSpriteNode()

    override func didMove(to view: SKView) {
        person = SKSpriteNode(imageNamed: "red_1.png")
        person.size = CGSize(width: 150, height: 129)
        person.position = CGPoint(x: 0, y: 0)
        person = SKSpriteNode(imageNamed: atlas.textureNames[0])

        for i in 1...atlas.textureNames.count {
            let Name = "red_\(i).png"
            TextureArray.append(SKTexture(imageNamed: Name))
        }

        self.addChild(person)
    }

    override func update(_ currentTime: TimeInterval) {
        let myAnimation = SKAction.animate(with: TextureArray, timePerFrame: 0.1)
        person.run(SKAction.repeatForever(myAnimation))
    }
1

There are 1 answers

8
JohnV On BEST ANSWER

The animation action is placed in update, which is executed once every frame. So if the game runs at 60 FPS, update gets called 60 times in one second. This means that every second person gets 60 new myAnimation actions that it needs to run.

To fix this, consider placing the animation action somewhere else in your code, e.g. right after adding the person to the scene. Since this is a repeatForever action, the animation will run as you intended until either the action is removed from the node, or the node is removed from the scene.

Hope this helps!