swiftsprite-kitskaction

Reversing each individual action in an SKAction sequence without reversing the order of all actions


I am trying to create a SKAction sequence and then reverse each of the actions individually, without reversing the overall order.

I originally tried this via the reverse() method in the SKAction object, but this is not quite what I want. From the documentation:

This action is reversible; it creates a new sequence action that reverses the order of the actions. Each action in the reversed sequence is itself reversed. For example, if an action sequence is {1,2,3}, the reversed sequence would be {3R,2R,1R}.

I require {1R,2R,3R} as the new action instead. For example, if I had:

let rotate = SKAction.rotate(byAngle: -CGFloat.pi / 2, duration: 0.5)
let scale = SKAction.scale(by: 2, duration: 0.5)
let action = SKAction.sequence([rotate, scale])

I would want to apply some function to the action action to produce a new action, which is equivalent to:

let rotate = SKAction.rotate(byAngle: CGFloat.pi / 2, duration: 0.5)
let scale = SKAction.scale(by: 0.5, duration: 0.5)
let action = SKAction.sequence([rotate, scale])

Is there a way this could be achieved without programming this flipped action seperately? To do this, I thought a possibility could be to break the sequence back down into its individual actions, reverse them, and build a new action from these, but I can't seem to find a way to break rotation back down into the two individual rotations again.


Solution

  • You could do this by creating another sequence but with the actions reversed, so:

    let actionReversed = SKAction.sequence([rotate.reversed(), scale.reversed()])
    

    If you wanted to run the actions "forward", on completion "reverse" them, you could use something like this:

      yourspritenode!.run(action) { [self] in
        yourspritenode!.run(actionReversed)
      }