JustAnotherGuy JustAnotherGuy - 13 days ago 4
Swift Question

What does self.addChild Do?

This is sort of a stupid question, but what does the function

self.addChild()
do?

I am familiar with this function, and how to use it, but I am not exactly sure what it adds the child to.

For instance, I have created and designed an
SKShapeNode
called
spinnyNode
. Then I call the function:

func touchDown(atPoint pos : CGPoint) {
if let n = self.spinnyNode?.copy() as! SKShapeNode? {
n.position = pos
n.strokeColor = SKColor.black
self.addChild(n)
}


What is the parent in this situation? Is it the view that the node is being created in?

Thank you so much for your time, and your answering of stupid questions.

Nik Nik
Answer

Lets break it down:

self in this case, refers to the SKScene which your are currently in. So if you're in your gameScene, the node will be added to the gameScene. Note that you can add nodes to other nodes, so if you have an SKNode named gameLayer, you could add a node to gameLayer, which would then be added to the scene. (That would look like this: gameLayer.addChild(node)) If there is no specified location for the node, it default chooses self

addChild(node) is the function that actually adds the specified node to the specified location (see above). You tell the compiler which node to add to the scene by putting its declared name in the brackets.

Make sure you're setting the nodes attributes (position, size, etc...), as they stay the default values until you change them.