0

I can't get the a sub class of SKShapeNode to accept an initialiser. To work around this I've tried to go by the example posted here Adding Convenience Initializers in Swift Subclass. The code i'm using is below.

class Ground1 : SKShapeNode {

override init() {
    super.init()
    print("Hello1")
}

convenience init(width: CGFloat, point: CGPoint) {
    var points = [CGPoint(x: -900, y: -300),
                  CGPoint(x: -600, y: -100),
                  CGPoint(x: -100, y: -300),
                  CGPoint(x: 2, y: 150),
                  CGPoint(x: 100, y: -300),
                  CGPoint(x: 600, y: -100),
                  CGPoint(x: 900, y: -300)]
    self.init(splinePoints: &points, count: points.count)
    lineWidth = 5
    strokeColor = UIColor.orange
    physicsBody = SKPhysicsBody(edgeChainFrom: path!)
    physicsBody?.restitution = 0.75
    physicsBody?.isDynamic = false
    print("Hello2")
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

}

When initialised the convenience init() is ignored and not used. Resulting in no shape being added to the scene. What am I doing wrong ?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
hoboBob
  • 832
  • 1
  • 17
  • 37
  • 1
    What code did you use to add the ground? – Sweeper Dec 30 '17 at 00:41
  • I create an instance of it in the gameScene, let ground = ground1(), then I add the instance to the scene. Addchild(gound). I get the print hello1 in the console but no print hello2 – hoboBob Dec 30 '17 at 08:21
  • Try this `let ground = Ground1(width: 10, point: CGPoint.zero)` and `addChild(ground)`. You can delete the `override init() {...}` and `required init {...}`. – 0x141E Dec 30 '17 at 09:55

1 Answers1

0

Thanks to 0x141E, who roundabout pointed me in the right direction. I found this worked but the code looks messy. The reasons for going about the initialisation this way is explained in detail here Adding Convenience Initializers in Swift Subclass. Although I was thrown out of finding a solution because of the use of splinePoints and assigning to a path.

class Ground1 : SKShapeNode {

    override init() {
        super.init()
    }

    convenience init(name: String) {
        var points = [CGPoint(x: -900, y: -300),
                      CGPoint(x: -600, y: -100),
                      CGPoint(x: -100, y: -300),
                      CGPoint(x: 2, y: 150),
                      CGPoint(x: 100, y: -300),
                      CGPoint(x: 600, y: -100),
                      CGPoint(x: 900, y: -300)]
        self.init(splinePoints: &points, count: points.count)
        lineWidth = 5
        strokeColor = UIColor.orange
        physicsBody = SKPhysicsBody(edgeChainFrom: self.path!)
        physicsBody?.restitution = 0.75
        physicsBody?.isDynamic = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}
hoboBob
  • 832
  • 1
  • 17
  • 37