How to subclass a SKShapeNode and init it as a circle

I've found it almost all convenience inits in the SKShapeNode class and it gives me difficulty to make a custom class subclassed from SKShapeNode, comparing to subclassing a SKSpriteNode. Currently my only solution to this is, subclass a sprite node and add a shape node as a child in it, but it of course looks bad.

By the way, I use Swift, so if it is needed for explaination, codes written in Swift will greatly help me.

Accepted Answer

If I understand you correctly, you'd like to subclass SKShapeNode to make circles with less scene code, is that right? Here is an example of such a sublass:


import SpriteKit
class CircleNode: SKShapeNode {
  
    init( radius: CGFloat, lineWidth: CGFloat, fillColor: SKColor, strokeColor: SKColor ) {
        super.init()
        let myPath = CGPathCreateMutable()
        CGPathAddArc( myPath, nil, 0,0, 15, 0, CGFloat( M_PI * 2.0 ), true )
        path = myPath
        self.lineWidth = lineWidth
        self.fillColor = fillColor
        self.strokeColor = strokeColor
        glowWidth = 0.5
    }
  
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


Scene code that uses the CircleNode:


    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch in touches {
            let location = touch.locationInNode(self)
            let sprite = CircleNode(radius: 50.0, lineWidth: 5.0, fillColor: SKColor.blackColor(), strokeColor: SKColor.redColor() )
            sprite.position = location
            self.addChild(sprite)
        }
    }

Thanks, your answer helps me a lot!

Needs to be updated for Swift 3.


Also what are you using an objective-c call in swift? why don't you use a pure swift solution?

Cocoa and SpriteKit were both written in Obj-C

How to subclass a SKShapeNode and init it as a circle
 
 
Q