Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subclass an SKNode to initialize it with a predetermined size

SKScene is a subclass of SKNode and we can initialize it with a certain size. But SKNode itself lacks this ability and its size is the smallest rectangle that contains the children. Sometimes I need my SKNode to stretch to the window no matter how small the contents are. Therefore I would like to be able to customize SKNode class by adding the ability to set its size. Do you have any idea how?

like image 851
Mikayil Abdullayev Avatar asked Feb 17 '14 19:02

Mikayil Abdullayev


1 Answers

Oddly enough, there doesn't seem to be a way to do this built into sprite kit. You may have to settle by adding a transparent SKSpriteNode to your node:

- (id)initWithSize:(CGSize)size{
    self = [super init];
    if (self) {
        SKSpriteNode *node = [SKSpriteNode spriteNodeWithColor:[UIColor colorWithWhite:1.0 alpha:0.0] size:size];
        [self addChild:node];
        node.zPosition = -1;
        node.name = @"transparent";
        node.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
    }
    return self;
}

Now you can initialize it to the size you want, you would just have to be sure to change the transparent nodes size if you wanted to change the nodes size.

like image 78
Andrew97p Avatar answered Oct 10 '22 08:10

Andrew97p