Alexis Taugeron

Spring Animations With SpriteKit

I really like how simple it is to make bouncy animations with UIKit since the addition of UIView’s animateWithDuration:delay:options:usingSpringWithDamping:initialSpringVelocity: in iOS 7. I looked for something similar in SpriteKit but couldn’t find anything.

You could concatenate a few actions with the right duration and timingMode (or timingFunction since iOS 8), but it’s very unconvenient and hard to get good results this way. My understanding is that Apple wants you to use SKAction’s customActionWithDuration:actionBlock: for such cases, but you still have to do the maths in your action block…

I hope something easier to use will be added to SpriteKit in a future release, but in the meantime I made a small set of extensions for SKAction that implement spring animations.

The code is available on GitHub, feel free to use it: https://github.com/ataugeron/SpriteKit-Spring

The damping behavior is implemented in a generic way with a set of methods that use customActionWithDuration:actionBlock: to animate an arbitrary CGFloat key path on a SKNode. Then most SKAction factory methods have been mirrored to accept the usingSpringWithDamping:initialSpringVelocity parameters.

With these extensions, it’s super easy to make your existing animations bouncy. Let’s say I have this code to make a sprite pop:

1
2
3
4
5
mySprite.setScale(0)

let popAction = SKAction.scaleTo(1, duration: 1)

mySprite.runAction(popAction)

Then I just need to add a few parameters to make it bouncy:

1
2
3
4
5
mySprite.setScale(0)

let popAction = SKAction.scaleTo(1, duration: 1, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0)

mySprite.runAction(popAction)

Another good thing is that the behavior is consistent with UIKit so if you have a bit of UIKit and a bit of SpriteKit in your app, you can bounce everything the same way. I tested the parameters with a UIView and a SKSpriteNode side by side and tried to have the animations match the best I could.

I hope this will be useful for someone (it sure will for me!). Don’t hesitate to ping me if you have any question or suggestion.