Search code examples
swiftsprite-kitskspritenodeaddchild

How to add sub-child to a child of self in swift


I am trying to add two SKSpriteNodes with their respective textures in swift, however the "Blade" does not show up on screen during the simulation. I am having no trouble getting the "Handle" to appear though. So my question is, what is the proper way to add a child of a child of self in swift so that everything works as intended?

    var Handle = SKSpriteNode(imageNamed: "Handle.png")
    var Blade = SKSpriteNode(imageNamed: "Blade.png") 

    override func didMoveToView(view: SKView) {
    Handle.position = CGPointMake(self.size.width / 2, self.size.height / 14)
    Blade.position = CGPointMake(Handle.position.x, Handle.position.y + 124)

    self.addChild(Handle)
    Handle.addChild(Blade)
}

Solution

  • This should get you close to where you expected it.

    Blade.position = CGPointMake(0, 124)
    

    Keep in mind when you add a sprite to another sprite the position is the position "within" that sprite. If you don't change the anchor that starts at the center of its parent. So you were starting in the center of Handle and adding half the width of the scene. Because Handle was already centered in the scene blade was off the scene.

    Hopefully that makes sense and is helpful.

    Also as lchamp mentioned you should lowerCamelCase

    var Blade = SKSpriteNode(imageNamed: "Blade.png") 
    

    This will help you in the future identifying Classes vs Variables.