how to add SKSpriteNode in a loop

1.3k Views Asked by At

I want to add some squares in a scene by loop. But this code has a problem. What is wrong?

var shape = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 100, height: 100))

for (var i=0 ; i<10 ; i++)
    {
        shape.name = "shape\(i)"
        shape.position = CGPointMake(20,20)
        self.addChild(shape)
    }
1

There are 1 best solutions below

2
On

You have a few issues here. With your current code you are trying to add a same SKSpriteNode multiple times to the same parent (scene). Which is impossible because one node can have only one parent at the time. Another thing, which is not an issue, but it can confuse you is that you are adding multiple nodes at same position so it can looks like only one node is added.

What you have to do is to create a copies of "shape" variable and add them accordingly to the scene, like this:

import SpriteKit

class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        var shape = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 20, height: 20))


        for (var i=0 ; i<10 ; i++)
        {

            var sprite = shape.copy() as SKSpriteNode

            sprite.name = "shape\(i)"
            sprite.position = CGPointMake(20 + CGFloat(i*30) , CGRectGetMidY(self.frame) )
            self.addChild(sprite)
        }


    }

}

Otherwise if you run your code, you will get error about adding a node which already has a parent. Hope this helps to understand what's happening.

Not related to all this, but you may find it useful to enable debugging labels (if you haven't already) in your view controller to see information like node count, draws count, visual physics representation and some more. This can save you from some future headaches. Here is how you enable all that:

(in viewDidLoad method or whatever method you use to initialize the scene):

skView.showsFPS = true
skView.showsNodeCount = true
skView.showsPhysics = true
skView.showsDrawCount = true