3

Why it's possible to instantiate a SKShapeNode like this

let circle = SKShapeNode(circleOfRadius: 10)

But when i want to create a class that inherit form SKShapeNode i cant do something like this:

public class Player:SKShapeNode{

public var playerName : String
private var inventory: [enumObject]

init(nameOfPlayer:String, position:CGPoint, radious: CGFloat) {

super.init(circleOfRadius: radious)
self.position = position
self.fillColor = SKColor.white

playerName = nameOfPlayer

inventory = [enumObject]()
}

}

It says that this init is not the designed init for SKShapeNode, I searched about it but couldn't find the right way of creating this damn circle.

GGirotto
  • 848
  • 2
  • 10
  • 31

1 Answers1

3

SKShapeNode.init(circleOfRadius:) is a convenience initializer on SKShapeNode so you can't call it from a Swift initializer. Swift enforces the designated initializer pattern more strictly than Objective C does.

Unfortunately, it appears the designated initializer for SKShapeNode is just init, so you'll need to do something like this:

public class Player: SKShapeNode {
    public var playerName : String
    private var inventory: [enumObject]

    init(nameOfPlayer:String, position:CGPoint, radius: CGFloat) {
        playerName = nameOfPlayer
        inventory = [enumObject]()

        super.init()

        self.path = CGPath(ellipseIn: CGRect(origin: .zero, size: CGSize(width: radius, height: radius)), transform: nil)

        self.position = position
        self.fillColor = SKColor.white
    }

    // init?(coder:) is the other designated initializer that we have to support
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

The code above works for subclassing SKShapeNode, but given the API that Apple provides and considering how your code might need to change in the future, it might make more sense to create an SKNode subclass that contains one or more SKShapeNodes. In this setup, if you wanted to represent the player as more than just a simple circle, you could simply add additional nodes to the player node.

Dave Weston
  • 6,527
  • 1
  • 29
  • 44