Search code examples
iosobjective-csprite-kitsknode

SKNode subclass with custom init method


I'm trying to subclass an SKNode class by using a custom init method. My custom init method looks like this:

//interface
@interface BlocksLayer : SKNode
-(instancetype)initWithDirection(BlocksLayerMotionDirection)direction;
@end

//implementation
-(instancetype)initWithDirection:(BlocksLayerMotionDirection)direction{
    self=[super init];
    if (self) {
       self.direction=direction;
       [self makeLayer];
     }
     return self;  
}

-(void)makeLayer{
    //scene size has always width=0 and height=0
    NSLog(@"%f",self.scene.size.width);
    NSLog(@"%f",self.scene.size.height);
}

When I initialize the class with my custom method scene.width and scene.height are always zero.
Instead if I use the static node method initialization the scene.size contains valid values.
Do you have any idea what is the problem?
Is this a correct way to subclass a SKNode and is it a valid strategy to implement a non-static custom initialization method?
Many thanks,
Domenico


Solution

  • As far as I can tell, the [SKNode node]; method sets up the self.scene property (with most likely default values, something like 1024x768). The code you provided doesn't create the self.scene property, and therefore it doesn't have default values.

    When the SKNode is added to the scene, the self.scene property will point to the SKScene that it was added to (this will always point to the root SKScene even if it is nested like SKScene->SKNode->SKNode). Then you can read the self.scene.size to get the size of the scene.

    If you need to read the values before adding to the scene, you can do:

    1. Pass in a reference to the SKScene in your custom init method and set self.scene to it.

    2. You can pass the size in as a parameter.

    3. You can hard code it in.

    These are ranked by what I would do.