Fiducial13
Fiducial13

Reputation: 1123

Calling a second function once the first function has completed it's SKAction repeat count using Swift

I have this function:

func midGroundlevelMovingSlow() {

    let moveLevelImage = SKAction.moveByX(-self.frame.size.width, y: 0, duration: gameSpeed)
    let replaceLevelImage = SKAction.moveByX(self.frame.size.width, y: 0, duration: 0)
    let movingAndReplacingLevelImage = SKAction.repeatAction(SKAction.sequence([moveLevelImage,replaceLevelImage]), count: 5)

    mgImage.runAction(movingAndReplacingLevelImage)
    mgImage2.runAction(movingAndReplacingLevelImage)
}

Once this has completed it's loop of 5, I wish to call this function:

func midGroundlevelMovingMedium() {

    let moveLevelImage = SKAction.moveByX(-self.frame.size.width, y: 0, duration: gameSpeed * 2)
    let replaceLevelImage = SKAction.moveByX(self.frame.size.width, y: 0, duration: 0)
    let movingAndReplacingLevelImage = SKAction.repeatAction(SKAction.sequence([moveLevelImage,replaceLevelImage]), count: 5)

    mgImage.runAction(movingAndReplacingLevelImage)
    mgImage2.runAction(movingAndReplacingLevelImage)
}

Can someone help me sort this out?

Thanks,

Steven

Upvotes: 2

Views: 251

Answers (1)

Moriya
Moriya

Reputation: 7906

SKSpriteNode has a run action function with a completion handler.

sprite.runAction(action: SKAction) { () -> Void in
        // call next function
    }

You can in that completion handler run your next method.

In your case where you want to wait for both functions to complete you could use a counter and check if both has completed before calling the next method.

something like

func midGroundlevelMovingSlow(completion: (()->Void)?) {

    let moveLevelImage = SKAction.moveByX(-self.frame.size.width, y: 0, duration: gameSpeed)
    let replaceLevelImage = SKAction.moveByX(self.frame.size.width, y: 0, duration: 0)
    let movingAndReplacingLevelImage = SKAction.repeatAction(SKAction.sequence([moveLevelImage,replaceLevelImage]), count: 5)

    var callCount = 2

    mgImage.runAction(movingAndReplacingLevelImage){ () -> Void in
        if --callCount == 0 {
            completion?()
        }
    }

    mgImage2.runAction(movingAndReplacingLevelImage){ () -> Void in
        if --callCount == 0 {
            completion?()
        }
    }
}

Upvotes: 1

Related Questions