kag359six
kag359six

Reputation: 2253

Why is SKSpriteNode.addChild() not working

I'm trying to add the "virus" as a child of the "cell", however only the cell appears. I tried adding both to the scene and then adding cell to virus, but the program broke. What is the proper way to add a child to an existing SkSpriteNode?

 override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    let virus : VirusNode = VirusNode.create(CGPoint(x: self.frame.maxX / 2, y: self.frame.maxY / 2))
    let cell = SKShapeNode(circleOfRadius: CGFloat(10))
    cell.fillColor = UIColor.greenColor()
    cell.position = CGPoint(x: self.frame.maxX / 2, y: self.frame.maxY / 2)
    cell.addChild(virus) //virus is just a SKSpriteNode
    self.addChild(cell)

}

Upvotes: 0

Views: 1132

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

Your issue is you need to understand how frame works when dealing with parent child relationships.

The child's frame will always be in the coordinate system of the parent, so when you create your virus. You need to keep this in mind.

As of right now you are setting your virus to the center of the scene. You then set your cell at the center of the scene. When you add the virus to the cell, you are changing the frame to be the location of the parent (Center of the screen) + location of the child (Center of the screen), which puts the virus on the top right of the scene. Which is not what you want.

Instead, set the virus at position (0,0). When you add it to cell, you will find that he is located in the center of your cell.

In regards to the program crashing, if you add an SKNode to another SKNode(or SKScene), you need to remove it from its parent before you can give it to another SKNode. Think of your job like child protective services, you need to remove the child from his original home before you can give the child to his new parents, otherwise you may end up with a wicked confrontation between the two parents that you can't control.

Upvotes: 2

Related Questions