SKLabelNode移动。但行动不重复

时间:2016-10-21 14:12:19

标签: swift sprite-kit sklabelnode

我创建了一个测试场景来练习一些基本的Swift 3和SpriteKit。在进入更复杂的目标之前,我试图通过理解基础知识来学习。

这里我创建了一个SKLabelNode,然后向左移动。我创建了一个重复动作的序列,但它不起作用。请你帮我理解失败的地方。 NodeCount指出只有一个节点。

import SpriteKit
import GameplayKit

class GameScene: SKScene {

var testShape = SKLabelNode()

override func didMove(to view: SKView) {

    func createShape() {

        testShape = SKLabelNode(text: "TEST")
        testShape.position = CGPoint(x: 0.5, y: 0.5)
        testShape.zPosition = 1
        addChild(testShape)

    }

    let moveTestShape = SKAction.moveBy(x: -500, y: 0, duration: 5)

    func repeater() {

        createShape()

        testShape.run(moveTestShape)

    }

    let delay = SKAction.wait(forDuration: 2)

    let repeatingAction = SKAction( repeater() )

    let sequence = SKAction.sequence([ delay, repeatingAction ] )

    run(SKAction.repeatForever(sequence))

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

}

override func update(_ currentTime: TimeInterval) {

}
}

1 个答案:

答案 0 :(得分:1)

您是否收到编译错误?

为什么要在didMoveToView中创建方法?

您的代码看起来应该更像

 class GameScene: SKScene {

       var testShape = SKLabelNode()

       override func didMove(to view: SKView) {

            let delay = SKAction.wait(forDuration: 2)
            let repeatingAction = SKAction.run(repeater)
            let sequence = SKAction.sequence([ delay, repeatingAction ] )
            run(SKAction.repeatForever(sequence))
       }

       func createShape() {

           testShape = SKLabelNode(text: "TEST")
           testShape.position = CGPoint(x: 0.5, y: 0.5)
           testShape.zPosition = 1
           addChild(testShape)
       }

       func repeater() {

            createShape()

            let moveTestShape = SKAction.moveBy(x: -500, y: 0, duration: 5)
            testShape.run(moveTestShape)
      }
 }

这就是你在SKActions中调用函数/代码块的方法。

let repeatingAction = SKAction.run(repeater)

let repeatingAction = SKAction.run { 
    repeater() 
}

还记得我们只重复新标签的生成动作。移动标签的实际操作不重复。所以你应该看到的是1个标签被创建并移动一次,而不是2秒后新标签被创建并移动一次等等

希望这有帮助