iosswiftsprite-kitskaction

How to synchronize textures animation and sound in SpriteKit


I'm creating a RPGGameKit using SpriteKit to help me develop my iOS games. Now that my player can move, I added animations and an audio system.

I ran on a problem to synchronize textures and sounds. Like a step when my player walk.

let atlas = SKTextureAtlas(named: "Walk")
let textures = atlas.getTextures() // I created an extension that returns textures of atlas

let walkingAnimation = SKAction.animate(with: textures, timePerFrame: 1)

So, walkingAnimation will loop through textures and change it every 1 second.

Now, I want to play a walking sound when the texture changes.

I have look at SKAction and SpriteKit documentation but there is no callback for this SKAction.

If you want to try to get this done with me or you have ideas of how to do it, please leave a comment.

Thanks :)


Solution

  • So, for now I'm going to do it like this :

    let textures = SKTextureAtlas(named: "LeftStep").getTextures()
    var actions = [SKAction]()
    
    for texture in textures {
        
        let group = SKAction.group([
            SKAction.setTexture(texture),
            SKAction.playSoundFileNamed("Step.mp3", waitForCompletion: false)
        ])
    
        let sequence = SKAction.sequence([
            group,
            SKAction.wait(forDuration: 0.5)
        ])
    
        actions.append(sequence)
    
    }
    
    self.node.run(SKAction.repeatForever(SKAction.sequence(actions)))
    

    Thanks @StefanOvomate