Search code examples
swiftskspritenode

How to add to an SKAction sequence a function which returns a void?


I am adding a particle emitter to an SKSpriteNode object (a ball) to make a trail as it moves. The following code returns the ball to its original location:

let moveAction = SKAction.move(to: CGPoint(x: origNP.x, y: origNP.y), duration: 0.3)
let doneTrail: Void = moveThis.removeAllChildren()
let sequence = SKAction.sequence([moveAction, doneTrail])
moveThis.run(sequence)

My goal being that I don't want to remove the emitter till the ball is back in its original spot. However the above code doesn't work because I get the error:

Cannot convert value of type 'Void' to expected element type 'SKAction'

So the way I do it now is:

let moveAction = SKAction.move(to: CGPoint(x: origNP.x, y: origNP.y), duration: 0.3)
let sequence = SKAction.sequence([moveAction])
moveThis.run(sequence)
moveThis.removeAllChildren()

But obviously the trail disappears before the ball is returned.

Is there a way to add a void returning method to an SKAction sequence?


Solution

  • When you want to turn a piece of code into an SKAction, so that you can put it into a sequence (or whatever other thing you want to do with it), you can use SKAction.run:

    let doneTrail = SKAction.run { moveThis.removeAllChildren() }
    

    Now that doneTrail is an SKAction, SKAction.sequence([moveAction, doneTrail]) should compile.