具有自定义 init 方法的 SKNode 子类

SKNode subclass with custom init method

我正在尝试使用自定义初始化方法子class SKNode class。 我的自定义初始化方法如下所示:

//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);
}

当我使用自定义方法初始化 class 时,scene.width 和 scene.height 始终为零。
相反,如果我使用静态 node 方法初始化 scene.size 包含有效值。
你知道问题出在哪里吗?
这是 subclass SKNode 的正确方法吗?它是实现非静态自定义初始化方法的有效策略吗?
非常感谢,
多梅尼科

据我所知,[SKNode node]; 方法设置了 self.scene 属性(最有可能的默认值,例如 1024x768)。您提供的代码不会创建 self.scene 属性,因此它没有默认值。

SKNode 添加到场景时,self.scene 属性 将指向它被添加到的 SKScene (这将始终指向root SKScene 即使它像 SKScene->SKNode->SKNode 这样嵌套)。 然后可以读取self.scene.size得到场景的大小

如果需要在添加到场景之前读取值,可以这样做:

  1. 在您的自定义初始化方法中传递对 SKScene 的引用并为其设置 self.scene

  2. 您可以将尺寸作为参数传入。

  3. 你可以硬编码进去。

这些是根据我会做什么来排名的。