2

I have a class that inherits from SKShapeNode because I want to add additional properties. The problem I am having is that I want to be able to create a "circle" by using SKShapeNode's "convenience" initializer SKShapeNode.init(circleOfRadius:CGFloat), but since it is a convenience initializer the compiler complains with a message " Must call a designated initializer of the class SKShapeNode", because it only allows calling of a "designated initializer" of the parent class, but the only "designated" initializer of SKShapeNode is SKShapeNode.init(), which would not create the circle shape i want. Below is my code with the compiler error. So the question is, can I subclass SKShapeNode and still somehow have access to the "convenience" initializer to initialize it with a circle shape? Seems to me that it is not possible. And so are there any workarounds?

thanks

enter image description here

Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189
malena
  • 798
  • 11
  • 26
  • I have added the tag `swift` to your question, because this kind of restriction on initialization of derived classes is a swift-specific feature (not present in Objective-C). – Nicolas Miari Dec 28 '15 at 01:45
  • Possible duplicate of [Adding Convenience Initializers in Swift Subclass](http://stackoverflow.com/questions/24373142/adding-convenience-initializers-in-swift-subclass) – Whirlwind Dec 28 '15 at 13:40

1 Answers1

0

The designated initializer for SKShapeNode is just plain old init, so that's what we have to call in our custom init method. To create a circle shape then, we will have to create the path ourselves. Fortunately, CGPath has a convenience initializer we can use to create the circle. Here ya go:

import SpriteKit

class CustomSKShapeNode:SKShapeNode{
    var groupName:String!

    init(groupName:String,radius:CGFloat){
        super.init()
        self.groupName = groupName
        let rect = CGRect(x:-radius,y:-radius,width:radius * 2,height:radius * 2)
        self.path = CGPath(ellipseIn: rect, transform: nil)
        self.fillColor = UIColor.yellow
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

var node = CustomSKShapeNode(groupName:"group1",radius:40)

node.position = CGPoint(x:40,y:40) // bottom left corner

addChild(node)
tonethar
  • 2,112
  • 26
  • 33