Search code examples
iosswiftsprite-kitnodesskaction

How to create repeating segments in swift spritekit


As you can see in the code below, I'm trying to establish a node at the bottom left corner of the screen, then make twenty more of them in a row so that they are directly next to each other and not stacked. However, this code is not working and is not showing the image I'm trying to put in. If somebody could please should some light on why this is not working and how I can fix it I would be grateful.

Yes, this function is being called just in a different part of the code

let obstacleSquare = SKSpriteNode(imageNamed: "obstaclesquare")
func createBottomBound() {
    obstacleSquare.position = CGPoint(x: 0 + frame.size.width/40, y: 0 + frame.size.width/40)
    obstacleSquare.size = CGSize(width: frame.size.width/20, height: frame.size.width/20)
    var i = 0
    while (i<20) {
        obstacleSquare.removeFromParent()
        addChild(obstacleSquare)
        obstacleSquare.run(SKAction.moveBy(x: obstacleSquare.size.width*CGFloat(i), y: 0, duration: 0))
        i += 1
    }
}

Solution

  • Hi look at the differences below

    func createBottomBound() {
        var i = 0
        while (i<20) {
            //Create a new instance here
            let obstacleSquare = SKSpriteNode(imageNamed: "obstaclesquare")
    
            /*I'm surprised your code ran as this line should of made it crash, you are asking it to remove the obstacle before you even added it. Any way you do not need this*/
            //obstacleSquare.removeFromParent()
    
            /*You don't want the objects stacked so you can change the position in the loop*/
            obstacleSquare.position = CGPoint(x: 0 + frame.size.width/(40 - i*2), y: 0 +     frame.size.width/(40 - i*2))
            obstacleSquare.size = CGSize(width: frame.size.width/20, height: frame.size.width/20)
            addChild(obstacleSquare)
            obstacleSquare.run(SKAction.moveBy(x: obstacleSquare.size.width*CGFloat(i), y: 0, duration: 0))
            i += 1
        }
    }