Apps – MMNodeActions Sprite Kit SKActions extension library

MMNodeActions is an iOS SKAction/SCNAction library extension which allows you to run sequential actions on multiple nodes directly on target SKNodes/SCNNodes.

Sprite Kit SKAction’s API is great to create powerful animations but we cannot achieve to have good code readability when running sequential code on multiple nodes.

To illustrate this, here is a sample code :

import SpriteKit

class GameScene: SKScene {

    weak var node1: SKNode!
    weak var node2: SKNode!

    override func didMove(to view: SKView) {
        super.didMove(to: view)
        cacheUI()
        runSampleSequence()
    }

    private func cacheUI() {
        // Fetch nodes from associated SKS file
        node1 = self.childNode(withName: "node1")!
        node2 = self.childNode(withName: "node2")!
    }

    private func runSampleSequence() {
        // I want node1 to fadeIn
        // then node2 to fadeIn
        // then node1 to fadeOut
        // then node2 to fadeOut
        node1.run(SKAction.sequence([
            SKAction.fadeIn(withDuration: 1),
            SKaction.run { [weak self] in
                self.node2.run(SKAction.fadeIn(withDuration: 2))
            },
            SKAction.fadeOut(withDuration: 4),
            SKaction.run { [weak self] in
                self.node2.run(SKAction.fadeOut(withDuration: 3))
            }
        ]))
    }
}

The above code will run perfectly, but will result with boilerplate code if we add node3, node4 …
I wanted to be able to refactor it to be easier to read and write business code.

So I created an extension library that allow you to run actions directly on SKNodes, that is :

self.run(SKAction.sequence([
    node1.fadeIn(withDuration: 1),
    node2.fadeIn(withDuration: 2),
    node1.fadeOut(withDuration: 4),
    node2.fadeOut(withDuration: 3)
]))

Check out the Github project to start using it !
MMNodeActions

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *