如何在 swift 中创建自定义 SKAction

How to create a custom SKAction in swift

我的想法是创建从天而降的方块。

为此,我需要一个执行四项操作的自定义操作:

  1. 用我的区块创建一个节点class
  2. 设置那个节点的位置
  3. 将节点添加到场景
  4. 稍等片刻后转到第一点

我想知道你是否真的可以创建一个 SKAction.customActionWithDuration 来做这些事情。

提前致谢

以下方法创建一个 SKAction 应该符合您的需要。

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)
    }
}

感谢@appsYourLife。 我在下面做了一些更改:

  1. 我调整了 swift 3

  2. 我添加了一个名为 parent 的参数,因此您可以使用 buildAction(parent: self) 或者如果您想将节点附加到其他节点,您可以使用 buildAction(parent: otherNode)

    func buildAction(parent: SKNode) -> SKAction {
      return SKAction.run {
    
      // 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
      parent.addChild(node)
    
      // 4. after a delay go to point one
      let wait = SKAction.wait(forDuration: 3)
      let move = SKAction.move(to: CGPoint(x: 500, y: 0), duration: 1)
      let sequence = SKAction.sequence([wait, move])
      node.run(sequence)
     }
    }