如何在swift中创建自定义SKAction

时间:2015-08-14 21:45:15

标签: swift sprite-kit skaction

我的想法是创造出从天而降的块。

要做到这一点,我需要一个自定义动作,它可以做四件事:

  1. 使用我的块类
  2. 创建一个节点
  3. 设置该节点的位置
  4. 将节点添加到场景
  5. 延迟后转到第一点
  6. 我想知道你是否真的可以创建SKAction.customActionWithDuration来做这件事。

    提前致谢

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

感谢@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)
     }
    }