Search code examples
swiftsprite-kitsklabelnode

SKLabelNode Moves. But action does not repeat


I have created a Test Scene to practice some basic Swift 3 and SpriteKit. I'm trying to learn by understanding the basics before moving on to more complex goals.

Here I have a SKLabelNode that is created and then moves to the left. I have created a sequence to repeat the action but it does not work. Please could you help me understand where it fails. NodeCount notes that there is only 1 node.

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

}
}

Solution

  • Are you not getting compiler errors?

    Why are you creating methods in didMoveToView?

    Your code should look more like this

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

    This is how you call functions/code blocks in SKActions.

    let repeatingAction = SKAction.run(repeater)
    

    or

    let repeatingAction = SKAction.run { 
        repeater() 
    }
    

    Also remember our are only repeating the spawn action for new labels. The actual action to move the labels is non repeating. So what you should see is 1 label created and moved once, than 2 seconds later a new label gets created and moved once etc

    Hope this helps