Subclassing SKShapeNode

I would like to create a subclass of SKShapeNode in order to draw triangles and add a little extra structure. I need to rotate these about the center of their bounding box, so would like to imitate the SKShapeNode init(path: CGPath, centered: Bool). However this is a convenience initializer and so cannot be accessed from the subclass. I dont have any difficulty defining the path in the subclass, but the question is how to get it centered? (SKShapeNode does not seem to have a property for this.)


import SpriteKit


class mySKShapeNode: SKShapeNode {

class mySKShapeNode : SKShapeNode {

override init( ) {

super.init( )

}

convenience init( path: CGPath, centered: Bool) {

self.init( )

self.path = path

// How to get it centered????

}

required init?(coder aDecoder: NSCoder) {

fatalError("init(coder:) has not been implemented")

}

}

}

Accepted Reply

I have found a workaround for this which may just be useful for someone using SKShapes. You can indeed create a subclass using the CGPath initializer (see above). If you want the resulting node to be centered you just need to adjust the path so that it begins and ends at the center - it's rather like evaluating a contour integral in complex analysis. Suppose you wish to create an instance of mySKShapeNode (see above) using the path joining the points (-50, -25), (50,-25) and ((0,25) so that the center of the instance is at (0,0). Do this by using the path (0,0), (0, -25), (50, -25), (0, 25), (-50, -25), (0, -25), (0, 0).

This seems to work fine: in particular zrotations will now be about this center.

Replies

Sorry - in copying and pasting I ended up with too many classes! Should have read


import SpriteKit


class mySKShapeNode : SKShapeNode {

override init( ) {

super.init( )

}

convenience init( path: CGPath, centered: Bool) {

self.init( )

self.path = path

// How to get it centered????

}

required init?(coder aDecoder: NSCoder) {

fatalError("init(coder:) has not been implemented")

}

}

I have found a workaround for this which may just be useful for someone using SKShapes. You can indeed create a subclass using the CGPath initializer (see above). If you want the resulting node to be centered you just need to adjust the path so that it begins and ends at the center - it's rather like evaluating a contour integral in complex analysis. Suppose you wish to create an instance of mySKShapeNode (see above) using the path joining the points (-50, -25), (50,-25) and ((0,25) so that the center of the instance is at (0,0). Do this by using the path (0,0), (0, -25), (50, -25), (0, 25), (-50, -25), (0, -25), (0, 0).

This seems to work fine: in particular zrotations will now be about this center.