Thomas Pereira Thomas Pereira - 14 days ago 9
Swift Question

How to create a custom SKAction in swift

The idea is that I am creating blocks that are falling out of the sky.

To do this I need an custom action that does four things:


  1. Create an node with my block class

  2. Set the position of that node

  3. add the node to the scene

  4. after an delay go to point one



I am wondering if you actually can create a
SKAction.customActionWithDuration
to do this things.

Thanks in advance

Answer

The following method creates an SKAction that should fit your needs.

func buildAction() -> SKAction {
    return SKAction.runBlock {
        // 1. Create a node: replace this line to use your Block class
        let node = SKShapeNode(circleOfRadius: 100)

        // 2. Set the position of that node
        node.position = CGPoint(x: 500, y: 300)

        // 3. add the node to the scene
        self.addChild(node)

        // 4. after a delay go to point one
        let wait = SKAction.waitForDuration(3)
        let move = SKAction.moveTo(CGPoint(x: 500, y: 0), duration: 1)
        let sequence = SKAction.sequence([wait, move])
        node.runAction(sequence)
    }
}