This doesn't work – the newNode's texture is nil:
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
SKSpriteNode *node = [SKSpriteNode spriteNodeWithColor:[UIColor orangeColor] size:CGSizeMake(100, 100)];
SKTexture *texture = [self.view textureFromNode:node];
SKSpriteNode *newNode = [SKSpriteNode spriteNodeWithTexture:texture];
[self addChild:newNode];
}
return self;
}
This does work:
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
SKSpriteNode *node = [SKSpriteNode spriteNodeWithColor:[UIColor orangeColor] size:CGSizeMake(100, 100)];
SKAction *createNewNode = [SKAction runBlock:^{
SKTexture *texture = [self.view textureFromNode:node];
SKSpriteNode *newNode = [SKSpriteNode spriteNodeWithTexture:texture];
[self addChild:newNode];
}];
[self runAction: createNewNode];
}
return self;
}
Can someone please explain why!? Thanks!
In case you're wondering why the node is not added the scene: The Apple documentation for textureFromNode states: "The node being rendered does not need to appear in the view’s presented scene."
My guess is: at the point where you are creating the sprite node (inside the scene's initWithSize:) the node graph is not fully set up yet. The scene isn't connected with (presented by) the view, and therefore it is not set up for rendering.
It's quite possible that SKSpriteNode textures for sprites using a color are only created after the scene is presented. This would explain why running the block action works.
You can probably fix this also by simply moving the code from initWithSize: to the scene's didMoveToView method, which is called after the scene was presented on the view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With