Lukas Köhl
Lukas Köhl

Reputation: 1579

SpriteKit: Add Multiple SKSpriteNodes To The Scene

I have an image which should be added multiple times to the scene directly in line (eg. a wall). For this I came up with a simple algorithm changing the x and y coordinates.

    func addBackground(){
    bg = SKSpriteNode(imageNamed: "background")
    let fieldsX = 5
    let fieldsY = 8
    var xPos = CGFloat()
    var yPos = CGFloat()
    let fieldsWidth = screenWidth / CGFloat(fieldsX)
    let sumField = fieldsX * fieldsY

    bg.size = CGSize(width: fieldsWidth, height: fieldsWidth)
    for(var i = 0; i < sumField; i++){
        bg.position = CGPoint(x: xPos, y: yPos)
        self.addChild(bg)
        xPos = xPos + fieldsWidth
        if(i % fieldsX == 0){
            yPos = yPos + fieldsWidth
            xPos = 0
        }
    }
}

So let me explain you my code. First I create a SKSpriteNode with the image. Afterwards there are a couple variables which I need to fill the scene. So I want the image to appear 5 times on the x-axis and 8 times on the y-axis. To make sure that they are on the same size, they are a square. Every time in the for-loop the x coordinate get higher by 1/5 of the screen. Every 5th loop the x coordinate gets reset and the y coordinate get 1/8 of the screen higher.All in all 40 nodes should be created and added to the scene. When I run the program I get an error in the AppDelegate because of an uncaught exception. It also says: Attemped to add a SKNode which already has a parent. Is there a way to add the 40 nodes to the scene without an error?

Upvotes: 2

Views: 494

Answers (1)

Alexey Pichukov
Alexey Pichukov

Reputation: 3405

You don't add many nodes to your Scene, you try to add one node 40 times, thats why on second time it node have a parent and you get the error. You need to create nodes obgects inside 'for'

Upvotes: 1

Related Questions