iosswiftanimationskaction

How to stop SKAction called on DidMove when a variable changes


So I'm loading and running an animation when my Scene starts, but there's a point in which I'd like to stop my animation. I do understand why it´s not working, but I cannot find a way to solve it. I've tried overriding func update, but I cannot find the correct way (if there is one) to update my function.

override func didMove(to view: SKView) {
    loadAnimation(atlasName: "test")
    runAnimation(spriteName: "testImg", timeFrame: 0.08)    
}

func loadAnimation(atlasName : String) {
    let spriteAtlas = SKTextureAtlas(named: "\(atlasName)")
    
    for index in 1...spriteAtlas.textureNames.count{
        let image = String(format: "\(atlasName)%01d", index)
        atlasAnimation += [spriteAtlas.textureNamed(image)]
    }

}

func runAnimation(spriteName : String, timeFrame : Double) {
    let spriteNode = self.childNode(withName: "\(spriteName)")
    spriteNode?.name = "\(spriteName)"
    if (spriteNode != nil) {
        let animation = SKAction.animate(with: atlasAnimation, timePerFrame: timeFrame)
        let forever = SKAction.repeatForever(animation)
        spriteNode?.run(forever, withKey: "key")
        if spriteNode?.name == "whatever" {
            if i  < 18 {
                spriteNode?.removeAction(forKey: "key")
            }
        }
    }

Solution

  • You can use a property observer for this kind of tasks:

    var i = 50{
       didSet{
          if i < 18{
              spriteNode.removeAction(forKey: "key")
          }
       }
    }      
    

    This means that everytime i is set to another value, the didSet block is called.