FernandoRosa FernandoRosa - 4 months ago 15
Swift Question

swift spritekit : How to stop a runBlock?

How can I stop all actions from a runBlock:

func slideShowControl () {


let noObject = SKSpriteNode()
noObject.name = "noObject"

addChild(noObject)



let block = SKAction.runBlock({

self.slideShow(1)
print("slide01")

self.runAction(SKAction.waitForDuration(5), completion: {

print("slide02")


})

self.runAction(SKAction.waitForDuration(8), completion: {

print("slide03")

})

...

self.runAction(SKAction.waitForDuration(17), completion: {

print("slide06")

})

})


noObject.runAction(block, withKey: "stop")


self.slideShow(1) just present a button to send the key "stop", but the block continues to run and print. Is possible to stop this block?

noObject.removeActionForKey("stop")

Answer

So you are naming an object "noObject" and an action "stop"? :)

Anyway, you should use a group and a few sequence actions.

The idea

This code

self.runAction(SKAction.waitForDuration(5), completion: {
    print("slide02")
})

can also be written this way

let action1 = SKAction.sequence([SKAction.waitForDuration(5), SKAction.runBlock { print("slide02") }])

Solution

Given a sprite

let sprite = SKSpriteNode()

and 4 actions

let action0 = SKAction.runBlock { print("slide01") }
let action1 = SKAction.sequence([SKAction.waitForDuration(5), SKAction.runBlock { print("slide02") }])
let action2 = SKAction.sequence([SKAction.waitForDuration(8), SKAction.runBlock { print("slide03") }])
let action3 = SKAction.sequence([SKAction.waitForDuration(6), SKAction.runBlock { print("slide06") }])

we can group the actions like this

let group = SKAction.group([action0, action1, action2, action3])

Now we can run the action with a key

sprite.runAction(group, withKey: "group")

and stop it

sprite.removeActionForKey("group")
Comments