Omer Harel
Omer Harel

Reputation: 283

How to create transition into SKAction?

i created function that change my background color every 10 seconds and i want to add transition when its change the color of the background.

Game Scene :

let wait = SKAction.waitForDuration(10)

        let block = SKAction.runBlock({
            [unowned self] in
            self.backgroundColor = UIColor.randomColor()
            })


        let sequence = SKAction.sequence([wait,block])

        runAction(SKAction.repeatActionForever(sequence), withKey: "colorizing")

thanks for help!

Upvotes: 1

Views: 92

Answers (1)

Whirlwind
Whirlwind

Reputation: 13675

You can do it like this:

override func didMoveToView(view: SKView) {

   colorize()
}


func colorize(){

     let colorize = SKAction.sequence([

          SKAction.colorizeWithColor(UIColor.randomColor(), colorBlendFactor: 1, duration: 3),

          SKAction.runBlock({[unowned self] in self.colorize()})
      ])

     runAction(colorize, withKey: "colorizing")
}

This is recursive function which calls itself every time colorizeWithColor action is finished. This is required due to fact that just repeating this:

 SKAction.colorizeWithColor(UIColor.randomColor(), colorBlendFactor: 1, duration: 3)

inside an action sequence will colorize the background always to the same color. That will happen because when you create an action once, you can't change it over time (you can change its speed or pause it for example, but you can't change a duration or any other passed parameter).Instead, we re-create the action associated with a certain key each time. And this is from the docs about actions associated with keys:

If an action using the same key is already running, it is removed before the new action is added.

So each time we run a new action, associated with "colorizing" key, the previous action is removed and there will be always only one action with that key.

Upvotes: 2

Related Questions