SKLabelNode 移动。但动作不重复

SKLabelNode Moves. But action does not repeat

我创建了一个测试场景来练习一些基本的 Swift 3 和 SpriteKit。在继续实现更复杂的目标之前,我正在尝试通过了解基础知识来学习。

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

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

}
}

你没有收到编译器错误吗?

为什么要在 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 中调用 functions/code 块的方式。

let repeatingAction = SKAction.run(repeater)

let repeatingAction = SKAction.run { 
    repeater() 
}

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

希望对您有所帮助